首先,我的数据集如下所示
我想做的是按 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访问器(accessor):
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
具有“直接”.hour
访问器,但是 Series
的 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')
关于python - 按小时对 Pandas 数据框进行分组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564333/