gpt4 book ai didi

python - Pandas TimeGrouper 问题 - "time"索引上的类型错误

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:13 24 4
gpt4 key购买 nike

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

我想使用 groupby 和 TimeGrouper 来按工作日、一天中的时间等绘制电子邮件数量,因此我将我的时间戳列设置为索引,但我得到一个 TypeError:“仅对 DatetimeIndex 有效, TimedeltaIndex 或 PeriodIndex,但得到了“索引”的实例”。我试过使用 to_datetime,但这会产生另一个 TypeError:“时间”类型的对象没有 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

最佳答案

Index: 150 entries 建议您的 index 列需要使用 pd.to_datetime() 转换为 datetime > 首先。

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

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

在设置索引之前。

关于python - Pandas TimeGrouper 问题 - "time"索引上的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36358730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com