我想要从我的收件箱中提取时间戳以便使用Pandas生成一些统计数据。我的代码获取了最多1000封电子邮件,并将时间戳存储在一个列表中。然后,我将该列表传递给pd.DataFrame,得到一个带有"time"类型列的数据框。
我想要使用groupby和TimeGrouper按周几、时间等来绘制电子邮件数量图表,所以我将我的时间戳列设为索引,但是我得到了一个TypeError:"仅针对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但获得了'Index'的实例"。我尝试使用to_datetime,但这会生成另一个TypeError:object of type 'time' has no len()。从我所看到的来看,df[0]已经是datetime对象,那么为什么在尝试使用TimeGrouper时会出错呢?
我想要使用groupby和TimeGrouper按周几、时间等来绘制电子邮件数量图表,所以我将我的时间戳列设为索引,但是我得到了一个TypeError:"仅针对DatetimeIndex、TimedeltaIndex或PeriodIndex有效,但获得了'Index'的实例"。我尝试使用to_datetime,但这会生成另一个TypeError:object of type 'time' has no len()。从我所看到的来看,df[0]已经是datetime对象,那么为什么在尝试使用TimeGrouper时会出错呢?
import win32com.client
import pandas as pd
import numpy as np
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
timesReceived = [message.SentOn]
for i in range(1000):
try:
message = messages.GetPrevious()
timesReceived.append(message.SentOn)
except(AttributeError):
break
df = pd.DataFrame(timesReceived);
df.set_index(df[0],inplace=True)
grouped = df.groupby(pd.TimeGrouper('M'))
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
编辑:添加 df.info() 和 df.head()。
df.info()
<class 'pandas.core.frame.DataFrame'>
Index: 150 entries, 04/01/16 09:37:07 to 02/11/16 17:40:56
Data columns (total 1 columns):
0 150 non-null object
dtypes: object(1)
memory usage: 2.3+ KB
df.head()
0
0
04/01/16 09:37:07 04/01/16 09:37:07
04/01/16 04:34:30 04/01/16 04:34:30
04/01/16 03:02:14 04/01/16 03:02:14
04/01/16 02:15:12 04/01/16 02:15:12
04/01/16 00:16:27 04/01/16 00:16:27
df.info()
和df.head()
的输出吗? - Stefanindex
列需要先使用pd.to_datetime()
转换为datetime
。df[0]
看起来像是datetime
,但需要进行类型转换,尝试在设置索引之前使用df[0] = pd.to_datetime(df[0], format='%m-%d-%Y %H:%M:%S')
进行转换。 - Stefandf[0] = pd.to_datetime(df[0], format='%m/%d/%y %H:%M:%S')
现在,df.info()
返回DatetimeIndex: 150 entries
。感谢您指出这一点。 - thobru