首页 > 解决方案 > 如何在分组后获得模式的计数?

问题描述

我有一个由三列组成的数据框,例如 orderid、time 和 status。每个订单都可以有许多状态,例如新的、已完成的、部分的、已取消的。所以订单 id 123 可以从新到取消等等等等,或者它可以有新的 10 次。

我的问题是在我按订单 ID 和时间完成分组后,如何找到每个订单状态模式的计数?例如……New, Filled 出现了多少次?新、新、已取消出现多少次?

我尝试了以下方法,但我只是不知道如何获得我想要的结果。

sortedOrders=OrdersAll.sort_values(['ordid','timestamp'], ascending=[True, True])
sortedOrdersAll.groupby(['ordid','ostatus']).count()

在此处输入图像描述

标签: pythonpandaspandas-groupby

解决方案


我创建了一个虚拟数据框 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


推荐阅读