【问题标题】:Pandas TimeGrouper issue - Typeerror on "time" indexPandas TimeGrouper 问题 - “时间”索引上的类型错误
【发布时间】:2016-07-21 09:38:51
【问题描述】:

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

我想使用 groupby 和 TimeGrouper 来按工作日、一天中的时间等绘制电子邮件数量,所以我将我的时间戳列设置为索引,但我得到一个 TypeError:“仅对 DatetimeIndex 有效, TimedeltaIndex 或 PeriodIndex,但获得了 'Index' 的实例”。我曾尝试使用 to_datetime,但这会产生另一个 TypeError:'time' 类型的对象没有 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() 的输出吗?
  • 当然,我已经编辑了我的帖子以包含它。谢谢
  • Index: 150 entries 建议您首先使用 pd.to_datetime() 将您的 index 列转换为 datetimedf[0] 可能看起来像datetime 但需要类型转换,请在设置为索引之前尝试df[0] = pd.to_datetime(df[0], format='%m-%d-%Y %H:%M:%S')
  • @Stefan 非常感谢。以下似乎已经成功了(稍微改变了格式字符串):df[0] = pd.to_datetime(df[0], format='%m/%d/%y %H:%M:%S')df.info() 现在返回DatetimeIndex: 150 entries。感谢您指出这一点。
  • 好的,已作为答案发布,因此可以将其标记为已解决。

标签: python python-2.7 pandas


【解决方案1】:

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

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

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

设置为索引之前。

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 2021-05-03
    • 2017-04-16
    • 2017-06-26
    • 1970-01-01
    • 2017-01-16
    • 2018-07-25
    • 2018-04-13
    相关资源
    最近更新 更多