以下是我的dataframe外观:
user_id time hour weekday location
updated_at
2019-09-02 05:29:00 29279 5:29:35 5 0 A
2019-09-02 05:29:00 29279 5:29:39 5 0 A
2019-09-02 05:29:00 29279 5:29:42 5 0 A
2019-09-02 05:29:00 29279 5:29:49 5 0 B
2019-09-02 05:32:00 29279 5:32:28 5 0 C
对于每一天,我要每个位置的每小时行和。
*想要实现这样的df.groupby(["month-day hour", "location]).count()
现在,我已经创建了附加列,该列加入了月日时间。
user_id time hour weekday location date-hour
updated_at
2019-09-02 05:29:00 29279 5:29:35 5 0 A 9-2 5
2019-09-02 05:29:00 29279 5:29:39 5 0 A 9-2 5
2019-09-02 05:29:00 29279 5:29:42 5 0 A 9-2 5
2019-09-02 05:29:00 29279 5:29:49 5 0 B 9-2 5
2019-09-02 05:32:00 29279 5:32:28 5 0 C 9-2 5
然后使用df.groupby(["date-hour", "location]).count()
,因为现在索引是“月-日时间”格式,所以我不能利用日期索引。
如果无法实现*,如何将“月-日时间”格式更改为更正日期时间。当我尝试pd.to_datetime("9-10 11")
时,它认为11是一年给我的Timestamp('2011-09-10 00:00:00')
发布于 2019-12-06 01:26:27
只需从datetime对象中删除分钟和第二个信息即可。这应该可以做到:
数据
df = pd.DataFrame([['2019-09-02 05:29:00', '29279', 'A'],
['2019-09-02 05:29:00', '29279', 'A'],
['2019-09-02 05:29:00', '29279', 'A'],
['2019-09-02 05:29:00', '29279', 'B'],
['2019-09-02 05:32:00', '29279', 'C']], columns = ['datetime', 'user_id', 'location'])
df['datetime'] = pd.to_datetime(df['datetime'])
print(df.to_string())
datetime user_id location
0 2019-09-02 05:29:00 29279 A
1 2019-09-02 05:29:00 29279 A
2 2019-09-02 05:29:00 29279 A
3 2019-09-02 05:29:00 29279 B
4 2019-09-02 05:32:00 29279 C
溶液
df['time_hour'] = df['datetime'].map(lambda x: x.replace(minute=0, second=0))
输出
print(df.groupby(['time_hour', 'location']).size().reset_index().to_string())
time_hour location 0
0 2019-09-02 05:00:00 A 3
1 2019-09-02 05:00:00 B 1
2 2019-09-02 05:00:00 C 1
发布于 2019-12-06 01:40:35
我相信你只需要df.index.floor('H')
和location
df_out = (df.groupby([df.index.floor('H'), 'location']).location.count()
.reset_index(1, name='count'))
Out[311]:
location count
updated_at
2019-09-02 05:00:00 A 3
2019-09-02 05:00:00 B 1
2019-09-02 05:00:00 C 1
https://stackoverflow.com/questions/59205562
复制相似问题