具有多个条件和分组依据的Python Pandas Count列

时间:2020-10-07 17:02:33

标签: python pandas dataframe vectorization

我有以下数据框

df = pd.DataFrame([
        ['LEhOc7XSE0','2020', '03', 'car'],
        ['LEhOc7XSE0','2020', '03', 'truck'],
        ['LEhOc7XSE0','2020', '03', 'bike'],
        ['LEhOc7XSE0','2020', '03', 'insurance'],
        ['LEhOc7XSE0','2020', '03', 'inspection'],
        ['iXC5AfJMox','2020', '04', 'car'],
        ['iXC5AfJMox','2020', '04', 'truck'],
        ['iXC5AfJMox','2020', '04', 'inspection'],
        ['XpLLAySojz','2020', '01', 'bike'],
    ], columns=['order_id','year', 'month', 'item_type'])

order_id列不是唯一的,并且在每一行中都描述了用此order_id购买了哪些商品。

现在,如果订单包含 order_idcar,那么我想计算任意数量的订单(唯一的bike是订单) ,但前提是该订单并非仅由这些商品组成。

df = pd.DataFrame([
        ['2020','03', '1'],
        ['2020','04', '1'],
    ], columns=['year', 'month', 'count_orders_with_condition'])

结果应该是这样,例如order_id = XpLLAySojz包含一个bike,但由于仅包含两个元素而被省略。 我正在处理的数据帧非常大,这就是为什么使用ìterrow()函数在这里表现很差的原因。我对熊猫为解决这个问题提供的可能性感到迷茫。

1 个答案:

答案 0 :(得分:0)

尝试:

import numpy as np

df['mask'] = np.where(df['item_type'].isin(['bike', 'car']), 1, 0)
mask = df.groupby('order_id')['mask'].nunique()
mask = mask.loc[mask.eq(2)]

res = df.set_index('order_id').loc[mask.index].reset_index().groupby(['year', 'month'])['order_id'].nunique()

输出:

>>> res

year  month
2020  03       1
      04       1
Name: order_id, dtype: int64