我有一个df,其中包含在接下来的10分钟内进行了多少次传输的信息。我想展示哪些银行在特定时间最受欢迎(我得出的结论是,由于中位数,我将能够展示这一点)。我的枢纽就是这样:
bank_name bank1 bank2 bank3 bank4
date
2019-11-03 102 105 78 81
00:00
2019-11-03 108 100 103 77
00:10
2019-11-03
00:20 108 134 55 27
... ... ... ... ...
2019-12-22
15:30 461 312 312 253
2019-12-22
15:40 396 361 376 229
或常规df
date bank_name transfers
2019-11-03 00:00 bank1 102
2019-11-03 00:00 bank2 105
2019-11-03 00:00 bank3 78
2019-11-03 00:00 bank4 81
2019-11-03 00:10 bank1 108
2019-11-03 00:10 bank2 100
... ... ...
我的期望值(我随机输入中值)
hour bank_name median
00 bank2 641
01 bank2 711
02 bank1 668
... ... ...
23 bank3 757
首先,我想对2019-11-03 00:00, 00:10, 00:20, 00:30, 00:40, 00:50
中的值求和并将其作为值03 00
。我是这样的:
df['date_'] = pd.to_datetime(df['date'].dt.strftime('%d %H'))
df = df.set_index('bank_name').groupby([ 'bank_name', 'date_']).agg({'transfers':np.sum})
...但是我不知道下一步该怎么做。感谢您的帮助。
答案 0 :(得分:1)
这就是我要怎么做。
import pandas as pd
df.groupby([pd.to_datetime(df['date']).dt.hour, 'bank_name'])['transfers'].median()
答案 1 :(得分:1)
尝试一下:
# median hourly transfer
hourly_transfers = df.groupby([pd.Grouper(key='date', freq='H'), 'bank_name']).median()
# which bank has the highest median in each hour
idx = hourly_transfers.groupby('date')['transfers'].idxmax()
# the result
hourly_transfers.loc[idx]
答案 2 :(得分:0)
所以听起来您需要:
类似这样的东西:
import datetime
df['date_hourly'] = df['date'].apply(lambda L: datetime(L.year, L.month, L.day, L.hour)) // [From here][1]
df_hourly = df.groupby(['date_hourly', 'bank_name']).transfers.sum().reset_index()
df_hourly['hour'] = df_hourly.date_hourly.apply(lambda x: x.hour)
df_pivot = df_hourly.groupby(['hour', 'bank_name']).transfers.median().reset_index()