我有一个由三列组成的数据框,例如订单编号,时间和状态。每个订单可以具有许多状态,例如新的,已填充的,部分的,已取消的。因此,订单ID 123可以从新订单到已取消订单等,也可以在其下有10次新订单。
我的问题是我按订单ID和时间进行分组后,如何找到每个订单状态模式的计数?例如,“新填充”出现几次?新,新,已取消出现几次?
我尝试了以下操作,但是我只是不知道如何获得想要的结果。
sortedOrders=OrdersAll.sort_values(['ordid','timestamp'], ascending=[True, True])
sortedOrdersAll.groupby(['ordid','ostatus']).count()
答案 0 :(得分:1)
我创建了一个虚拟数据帧df。您可以在下面参考获取状态模式计数的逻辑。
In [109]: status = 'new,filled,partial,cancelled'.split(',')
In [102]: df = pd.DataFrame( [ [ random.randint(1,25), random.randint(100, 200), status[random.randint(0,3)] ] for _ in range(50) ], columns=['order_id','timestamp' ,'status'])
In [103]: df.head(10)
Out[103]:
order_id timestamp status
0 20 120 new
1 9 118 cancelled
2 16 125 partial
3 9 124 cancelled
4 2 190 filled
5 3 185 partial
6 5 162 filled
7 21 101 new
8 25 115 filled
9 14 141 filled
In [104]: df_grouped = df.groupby('order_id', as_index=False)
In [105]: def status_transition_with_timestamp(each_grouped_df):
...: sorted_df = each_grouped_df.sort_values('timestamp', ascending=True)
...: concatenated_transition = ','.join(sorted_df['status'])
...: return concatenated_transition
...:
In [106]: result = df_grouped['status'].agg(status_transition_with_timestamp)
In [107]: result.head(10)
Out[107]:
order_id status
0 1 filled
1 2 filled,cancelled
2 3 partial,cancelled,partial
3 4 filled,new,cancelled
4 5 filled,cancelled
5 6 new
6 7 filled
7 9 partial,cancelled,cancelled
8 10 cancelled,new
9 11 new,partial
In [108]: result.groupby('status').count()
Out[108]:
order_id
status
cancelled,new 1
filled 4
filled,cancelled 2
filled,new,cancelled 1
filled,partial,partial 1
new 2
new,cancelled 2
new,filled 1
new,new,filled 1
new,new,new,partial,partial,cancelled,new 1
new,partial 1
partial 1
partial,cancelled,cancelled 1
partial,cancelled,partial 1
partial,partial 1
partial,partial,new,partial,new 1