gpt4 book ai didi

python - 如何对数据框中的 groupby 行应用计算并将结果 append 到数据框的底部?

转载 作者:太空宇宙 更新时间:2023-11-03 16:41:39 25 4
gpt4 key购买 nike

我正在尝试将简单计算的结果 append 到数据框中。我想按年份分组,然后计算收入减去税金以获得一组称为净收入的新记录。

import pandas as pd


data = {'year': [2010, 2011, 2012, 2011, 2012, 2010],
'item': ['Revenue', 'Revenue', 'Revenue', 'Tax', 'Tax', 'Tax'],
'value': [11, 8, 10, 3, 2, 3]}
dfRev = pd.DataFrame(data, columns=['year', 'item', 'value'])

print dfRev

   year     item  value
0 2010 Revenue 11
1 2011 Revenue 8
2 2012 Revenue 10
3 2011 Tax 3
4 2012 Tax 2
5 2010 Tax 3

我想像这样添加到底部。

   year     item  value
0 2010 Revenue 11
1 2011 Revenue 8
2 2012 Revenue 10
3 2011 Tax 3
4 2012 Tax 2
5 2010 Tax 3
6 2010 Net Revenue 8
7 2011 Net Revenue 5
8 2012 Net Revenue 7

我的实际数据有更多标题,即原产地、产品、国家/地区、项目、月份、值

我需要进行透视,以便它按原产地、产品、国家/地区、月份进行分组。然后将 item 扔到列中并将 Value 作为值。

最佳答案

您可以尝试枢轴:

#reshape so now you have a col for Tax and a col for Revenue
pivot = dfRev.pivot('year', 'item', 'value')
#perform the calculation
pivot.loc[:, 'Net Revenue'] = pivot.Revenue - pivot.Tax
#and then bring it back to the original shape
dfRev = pivot.stack().reset_index().sort_values(by='item')

print dfRev
year item 0
2 2010 Net Revenue 8
5 2011 Net Revenue 5
8 2012 Net Revenue 8
0 2010 Revenue 11
3 2011 Revenue 8
6 2012 Revenue 10
1 2010 Tax 3
4 2011 Tax 3
7 2012 Tax 2

关于python - 如何对数据框中的 groupby 行应用计算并将结果 append 到数据框的底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com