pandas - 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()
基本上,如果“批次”没有包含标签的项目,则会被过滤掉。
解决方案
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)])
推荐阅读
- python - 更新部署在 heroku 中的 json 文件中的数据
- amazon-web-services - 用于 EMR 的 EC2 - 在 XLarge、2XLarge 和 4XLarge 之间进行选择
- sql - SQL:包含 NULLS 的两列的总和?
- reactjs - 用于设置数组初始状态的类型
- c# - 如何使用 C# 使用 SharpDX 在 Helix 中放大和缩小?
- testing - 实例 scriptTableActor.open。当我在fitnesse中运行脚本时不存在错误
- python - 神经网络只在给定几个模式顺序时学习最后一个模式
- mysql - 如何使用 Jetbrains Exposed 库通过左连接添加单行?
- angular - 是否可以与已部署的 Angular 应用程序中的路由树进行交互?(Power BI/角度)
- ajax - React Native WebView:动态加载静态资源