[英]Add Dataframe Rows Based on Conditions of Other Rows
有没有办法根据 dataframe 中的其他行向 dataframe 添加行?
我有一个看起来像这样的 dataframe:
Year Month Project Account Value
2020 Jan abc Revenue 100
2020 Jan xyz Profit 20
2020 Jan abc Profit 10
2020 Jan xyz Revenue 350
我想对所有具有收入帐户的行执行计算,公式应该是成本 = 收入 - 相同的所有列(年、月、项目)的利润(所有行都是唯一的,所以只有一个每个计算的可能匹配)。
所以结果看起来像
Year Month Project Account Value
2020 Jan abc Revenue 100
2020 Jan xyz Profit 20
2020 Jan abc Profit 10
2020 Jan xyz Revenue 350
2020 Jan abc Cost 90
2020 Jan xyz Cost 340
我对 pandas 还是很陌生,但是在我完成的所有搜索中,我还没有找到使用 pandas 执行此操作的 pythonic 方法。 数据集非常大(100K+ 行),所以我宁愿不必迭代计算,但如果我不得不考虑使用另一个数据结构来存储 dataframe(如字典)并执行计算。
使用pivot
和stack
:
(df.pivot_table(index=['Year','Month', 'Project'],
columns=['Account'], values='Value'
)
.assign(Cost=lambda x: x['Revenue']-x['Profit'])
.stack().reset_index(name='Value')
)
Output:
Year Month Project Account Value
0 2020 Jan abc Profit 10
1 2020 Jan abc Revenue 100
2 2020 Jan abc Cost 90
3 2020 Jan xyz Profit 20
4 2020 Jan xyz Revenue 350
5 2020 Jan xyz Cost 330
尝试这个
grp = df.groupby(["Year", "Month", "Project", "Account"]).agg({"Value":"sum"}).reset_index()
costdf = grp.groupby(["Year", "Month", "Project"]).apply(lambda x: (x[x["Account"]=="Revenue"]["Value"].values[0] - x[x["Account"]=="Profit"]["Value"].values[0])).reset_index()
costdf.columns = ["Year", "Month", "Project","Value"]
costdf["Account"] = "Cost"
costdf = costdf[df.columns]
df = pd.concat([df,costdf])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.