mad*_*aks 3 python pandas pandas-groupby
首先,我的数据集如下所示
我想做的是按pickup_datetime小时分组.我在这里找到了相关的问题,但由于某种原因,解决方案似乎不起作用.我在下面列出了我的尝试.
我首先开始这样做:
df["dropoff_datetime"] = pd.to_datetime(df["dropoff_datetime"])
df["pickup_datetime"] = pd.to_datetime(df["pickup_datetime"])
test = df.groupby(df.hour).sum()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
AttributeError: 'DataFrame' object has no attribute 'hour'
Run Code Online (Sandbox Code Playgroud)
然后我尝试了这个:
test = df.groupby(df.dropoff_datetime.hour).sum()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
AttributeError: 'Series' object has no attribute 'hour'
Run Code Online (Sandbox Code Playgroud)
我有点困惑,因为看起来我的情况与上面提到的问题相同.我不知道为什么我会收到错误.任何帮助将非常感激
我们可以使用Series.dt.hour访问器:
test = df.groupby(df['pickup_datetime'].dt.hour).sum()
Run Code Online (Sandbox Code Playgroud)
以下是描述差异的示例:
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')
Run Code Online (Sandbox Code Playgroud)
如上所示DatetimeIndex具有"直接" .hour访问,但Series的datetimeD型细胞具有.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
Run Code Online (Sandbox Code Playgroud)
如果我们将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
Run Code Online (Sandbox Code Playgroud)
它成为了:
In [149]: type(df.index)
Out[149]: pandas.core.indexes.datetimes.DatetimeIndex
Run Code Online (Sandbox Code Playgroud)
所以我们可以.dt再次直接访问它(没有访问者):
In [148]: df.index.hour
Out[148]: Int64Index([13, 20], dtype='int64', name='Date')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2499 次 |
| 最近记录: |