python – Pandas TimeGrouper问题 – 关于“时间”索引的Typeerror

我试图从我的收件箱中提取时间戳,以便用Pandas生成一些统计信息.我的代码最多可以抓取1000封电子邮件,并将时间戳存储在列表中.然后我将列表传递给pd.DataFrame,它为我提供了一个类型为“time”的数据帧.

我想使用groupby和TimeGrouper来按工作日,时间等绘制电子邮件的数量,所以我将timestamp列设置为索引,但我得到一个TypeError:“仅对DatetimeIndex,TimedeltaIndex或PeriodIndex有效,但获得了“索引”的实例.我尝试过使用to_datetime,但是会生成另一个TypeError:’time’类型的对象没有len().据我所知,df [0]已经是一个日期时间对象,那么为什么在尝试使用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

最佳答案 索引:150个条目建议首先使用pd.to_datetime()将索引列转换为日期时间.

df [0]可能看起来像datetime但需要类型转换,请尝试

df[0] = pd.to_datetime(df[0], format='%m/%d/%Y %H:%M:%S') 

在设置索引之前.

点赞