首先,我的数据集如下所示
我想做的是通过pickup_datetime小时对列进行分组.我在here找到了相关的问题,但由于某种原因,解决方案似乎不起作用.我在下面列出了我的尝试.
我首先开始这样做:
df["dropoff_datetime"] = pd.to_datetime(df["dropoff_datetime"])
df["pickup_datetime"] = pd.to_datetime(df["pickup_datetime"])
test = df.groupby(df.hour).sum()
我收到以下错误:
AttributeError: 'DataFrame' object has no attribute 'hour'
然后我尝试了这个:
test = df.groupby(df.dropoff_datetime.hour).sum()
我收到以下错误:
AttributeError: 'Series' object has no attribute 'hour'
我有点困惑,因为看起来我的情况与上面提到的问题相同.我不知道为什么我会收到错误.任何帮助将非常感激
解决方法:
我们可以使用Series.dt.hour访问器:
test = df.groupby(df['pickup_datetime'].dt.hour).sum()
以下是描述差异的示例:
In [136]: times = pd.to_datetime(['2017-08-01 13:13:13', '2017-08-01 20:20:20'])
In [137]: times
Out[137]: DatetimeIndex(['2017-08-01 13:13:13', '2017-08-01 20:20:20'], dtype='datetime64[ns]', freq=None)
In [138]: type(times)
Out[138]: pandas.core.indexes.datetimes.DatetimeIndex
In [139]: times.hour
Out[139]: Int64Index([13, 20], dtype='int64')
如上所示,DatetimeIndex具有“direct”.hour访问器,但系列的datetime dtype具有.dt.hour访问器:
In [140]: df = pd.DataFrame({'Date': times})
In [141]: df
Out[141]:
Date
0 2017-08-01 13:13:13
1 2017-08-01 20:20:20
In [142]: type(df.Date)
Out[142]: pandas.core.series.Series
In [143]: df['Date'].dt.hour
Out[143]:
0 13
1 20
Name: Date, dtype: int64
如果我们将Date列设置为索引:
In [146]: df.index = df['Date']
In [147]: df
Out[147]:
Date
Date
2017-08-01 13:13:13 2017-08-01 13:13:13
2017-08-01 20:20:20 2017-08-01 20:20:20
它成为了:
In [149]: type(df.index)
Out[149]: pandas.core.indexes.datetimes.DatetimeIndex
所以我们可以再次直接访问它(没有.dt访问器):
In [148]: df.index.hour
Out[148]: Int64Index([13, 20], dtype='int64', name='Date')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。