如何有条件地聚合 pandas 查询的投影部分中的值?

How do I conditionally aggregate values in projection part of pandas query?

我目前有一个包含以下内容的 csv 文件:

 ID PRODUCT_ID        NAME  STOCK  SELL_COUNT DELIVERED_BY
1         P1  PRODUCT_P1     12          15          UPS
2         P2  PRODUCT_P2      4           3          DHL
3         P3  PRODUCT_P3    120          22          DHL
4         P1  PRODUCT_P1    423          18          UPS
5         P2  PRODUCT_P2      0           5          GLS
6         P3  PRODUCT_P3     53          10          DHL
7         P4  PRODUCT_P4     22           0          UPS
8         P1  PRODUCT_P1     94          56          GLS
9         P1  PRODUCT_P1      9          24          GLS

当我执行此 SQL 查询时:


    SELECT
      PRODUCT_ID,
      MIN(CASE WHEN DELIVERED_BY = 'UPS' THEN STOCK END) as STOCK,
      SUM(CASE WHEN ID > 6 THEN SELL_COUNT END) as TOTAL_SELL_COUNT,
      SUM(CASE WHEN SELL_COUNT * 100 > 1000 THEN SELL_COUNT END) as COND_SELL_COUNT
    FROM products
    GROUP BY PRODUCT_ID;

我得到了想要的结果:

PRODUCT_ID  STOCK   TOTAL_SELL_COUNT    COND_SELL_COUNT
P1          12      80                  113
P2          null    null                null
P3          null    null                22
P4          22      0                   null

现在我正在尝试使用 pandas 在该数据集上以某种方式获得相同的结果,这就是我正在努力解决的问题。

我将 csv 文件导入到名为 df_products 的 DataFrame 中。 然后我试了这个:

def custom_aggregate(grouped):

    data = {
        'STOCK': np.where(grouped['DELIVERED_BY'] == 'UPS', grouped['STOCK'].min(), np.nan)  # [grouped['STOCK'].min() if grouped['DELIVERED_BY'] == 'UPS' else None]
    }

    d_series = pd.Series(data)
    return d_series


result = df_products.groupby('PRODUCT_ID').apply(custom_aggregate)
print(result)

如您所见,我离预期结果还差得很远,因为我在根据 DELIVERED_BY 值使条件 STOCK 聚合工作时遇到问题。

这输出:

                           STOCK
PRODUCT_ID                      
P1          [9.0, 9.0, nan, nan]
P2                    [nan, nan]
P3                    [nan, nan]
P4                        [22.0]

这甚至不是正确的格式,但如果我能获得预期的 12.0 而不是 P1 的 9.0,我会很高兴。

谢谢


我只是想补充一点,我通过创建额外的列来接近结果:

df_products['COND_STOCK'] = df_products[df_products['DELIVERED_BY'] == 'UPS']['STOCK']
df_products['SELL_COUNT_ID_GT6'] = df_products[df_products['ID'] > 6]['SELL_COUNT']
df_products['SELL_COUNT_GT1000'] = df_products[(df_products['SELL_COUNT'] * 100) > 1000]['SELL_COUNT'] 

函数将如下所示:

def custom_aggregate(grouped):

    data = {
        'STOCK': grouped['COND_STOCK'].min(),
        'TOTAL_SELL_COUNT': grouped['SELL_COUNT_ID_GT6'].sum(),
        'COND_SELL_COUNT': grouped['SELL_COUNT_GT1000'].sum(),
    }

    d_series = pd.Series(data)
    return d_series


result = df_products.groupby('PRODUCT_ID').apply(custom_aggregate)

这是 'almost' 想要的结果:

            STOCK  TOTAL_SELL_COUNT  COND_SELL_COUNT
PRODUCT_ID                                          
P1           12.0              80.0            113.0
P2            NaN               0.0              0.0
P3            NaN               0.0             22.0
P4           22.0               0.0              0.0

通常我们可以将pandas写成如下

df.groupby('PRODUCT_ID').apply(lambda x : pd.Series({'STOCK':x.loc[x.DELIVERED_BY =='UPS','STOCK'].min(),
                                                 'TOTAL_SELL_COUNT': x.loc[x.ID>6,'SELL_COUNT'].sum(min_count=1),
                                                 'COND_SELL_COUNT':x.loc[x.SELL_COUNT>10,'SELL_COUNT'].sum(min_count=1)}))

输出[105]:

            STOCK  TOTAL_SELL_COUNT  COND_SELL_COUNT
PRODUCT_ID                                          
P1           12.0              80.0            113.0
P2            NaN               NaN              NaN
P3            NaN               NaN             22.0
P4           22.0               0.0              NaN