Pandas TimeGrouper问题 - 在“时间”索引上出现Typeerror

4
我想要从我的收件箱中提取时间戳以便使用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时会出错呢?
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() 的输出吗? - Stefan
当然,我已经编辑了我的帖子并包含在内。谢谢。 - thobru
“Index: 150 entries” 表示您的 index 列需要先使用 pd.to_datetime() 转换为 datetimedf[0] 看起来像是 datetime,但需要进行类型转换,尝试在设置索引之前使用 df[0] = pd.to_datetime(df[0], format='%m-%d-%Y %H:%M:%S') 进行转换。 - Stefan
@Stefan 非常感谢。以下代码似乎解决了问题(稍微更改了格式字符串): df[0] = pd.to_datetime(df[0], format='%m/%d/%y %H:%M:%S')现在,df.info() 返回 DatetimeIndex: 150 entries。感谢您指出这一点。 - thobru
好的,已发布为答案,可以标记为已解决。 - Stefan
1个回答

1

索引: 150 条记录 表明你的 index 列需要先使用 pd.to_datetime() 转换为 datetime 类型。

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

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

在设置为索引之前。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接