首页 > 解决方案 > groupby 与 str.contains 在不同的列

问题描述

df_batches = pd.DataFrame({"Item":['Can','Liquid','Label','Liquid2', 'Can', 'Sugar'],
                           "Unit_cost": [.14, .45, .17, 1, .16, 23],
                           "Product":['Prod1', 'Prod1', 'Prod1', 'Prod1', 'Prod1', 'Prod1'],
                           "Batch":['5,100','5,100','5,100','5,101','5,101','5,101'], 
                           "Total_cost": [452, 789.34, 11115.28, 3220.98, 3542, 512.34],
                           "Year": ['2019', '2019', '2019', '2019', '2019', '2019'],
                          })

我想使用这些规则创建一个 df:

如果批次中有任何项目str.contains('Label'),则在新的 groupby df 中获取这些批次。

试过这个:

label = df['Item'].str.contains('Label')
label_df = df[label].groupby(['Product', 'Batch', 'Item', 'Year'])[['Total_cost']].sum().reset_index()

但这只会得到str.contains('Label')行。

我假设我需要在.transform()某个地方使用,但无法弄清楚。

预期的输出是这样的:

df_output = pd.DataFrame({"Item":['Can','Liquid','Label'],
                           "Unit_cost": [.14, .45, .17],
                           "Product":['Prod1', 'Prod1', 'Prod1'],
                           "Batch":['5,100','5,100','5,100',], 
                           "Total_cost": [452, 789.34, 11115.28],
                           "Year": ['2019', '2019', '2019'],
                          })
label_df = df_output.groupby(['Product','Batch', 'Year', 'Item'])[['Total_cost']].sum().reset_index()

基本上,如果“批次”没有包含标签的项目,则会被过滤掉。

标签: pandaspandas-groupby

解决方案


IIUC 您要检索批号:

s = df.loc[df['Item'].str.contains('Label'), "Batch"].iat[0]

print (df.loc[df["Batch"]==s])

     Item  Unit_cost Product  Batch  Total_cost  Year
0     Can       0.14   Prod1  5,100      452.00  2019
1  Liquid       0.45   Prod1  5,100      789.34  2019
2   Label       0.17   Prod1  5,100    11115.28  2019

如果您有超过 1 个标签:

s = df.loc[df['Item'].str.contains('Label'), "Batch"]

print (df.loc[df["Batch"].isin(s)])

推荐阅读