Python 按小时分组数据帧的问题

Python 按小时分组数据帧的问题,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,首先,我的数据集如下所示 我想做的是按picku datetimehour对我的专栏进行分组。我在上找到了相关问题,但由于某种原因,解决方案似乎不起作用。我已经在下面列出了我的尝试 我首先从这个开始: df["dropoff_datetime"] = pd.to_datetime(df["dropoff_datetime"]) df["pickup_datetime"] = pd.to_datetime(df["pickup_datetime"]) test = df.groupby(df.

首先,我的数据集如下所示

我想做的是按
picku datetime
hour对我的专栏进行分组。我在上找到了相关问题,但由于某种原因,解决方案似乎不起作用。我已经在下面列出了我的尝试

我首先从这个开始:

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'
AttributeError: 'Series' object has no attribute 'hour'
然后我试了一下:

test = df.groupby(df.dropoff_datetime.hour).sum()
我得到了以下错误:

AttributeError: 'DataFrame' object has no attribute 'hour'
AttributeError: 'Series' object has no attribute 'hour'
我有点困惑,因为我的情况似乎和上面的问题一样。我不知道为什么我会出错。非常感谢您的帮助

我们可以使用访问器:

test = df.groupby(df['pickup_datetime'].dt.hour).sum()
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
下面是一个描述差异的示例:

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
访问器,但是
datetime
dtype的
Series
具有
.dt.hour
访问器:

test = df.groupby(df['pickup_datetime'].dt.hour).sum()
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
访问器):


需要
.dt
,因为使用
系列
-:


但如果
DatetimeIndex
,则忽略它-: