简体   繁体   English

总和 DataFrame 行值按列分组在另一个 DataFrame

[英]Sum DataFrame row values grouped by column in another DataFrame

I have two DataFrames as follows:我有两个 DataFrame,如下所示:

df2 = pd.DataFrame({ 
    'Code':['ABC','DEF','GHI','JKL','MNO'],       
    '2000': [19647.0, 1814135.0, 1864791.0,261630.0, 20758.0], 
    '2001': [1762621.0,1814135.0,1864791.0,1914573.0,1965598.0], 
    '2002': [25998340.0,26920466.0,207633.0,28813463.0,29784193.0] }) 
df2.set_index('Code')


df3 = pd.DataFrame({ 
    'Code':['ABC','DEF','GHI','JKL','MNO'],       
    'Groups': ['Group A', 'Group B', 'Group C','Group B', 'Group A']})
df3.set_index('Code')

I need to get total values for each year by the respective group.我需要按各个组获取每年的总值。 eg.例如。 the sum for the year 2000 for Group A is 40405.0. A 组2000 年的总和是 40405.0。

For the grouper map the index of df2 to the 'Groups' and then take the sum.对于石斑鱼map df2到“组”的索引,然后取总和。 Also you set the index you never assign it back so you should do df2=df2.set_index('Code') , though it's not necessary to have them as the index to solve this.此外,您设置了从未将其分配回来的索引,因此您应该执行df2=df2.set_index('Code') ,尽管不必将它们作为解决此问题的索引。

#df2=df2.set_index('Code')
#df3=df3.set_index('Code')
df2.groupby(df2.index.map(df3['Groups'])).sum()

#              2000       2001        2002
#Code                                     
#Group A    40405.0  3728219.0  55782533.0
#Group B  2075765.0  3728708.0  55733929.0
#Group C  1864791.0  1864791.0    207633.0

I would try something like this:我会尝试这样的事情:

df2 = pd.DataFrame({ 
'Code':['ABC','DEF','GHI','JKL','MNO'],       
'2000': [19647.0, 1814135.0, 1864791.0,261630.0, 20758.0], 
'2001': [1762621.0,1814135.0,1864791.0,1914573.0,1965598.0], 
'2002': [25998340.0,26920466.0,207633.0,28813463.0,29784193.0] }) 


df3 = pd.DataFrame({ 
'Code':['ABC','DEF','GHI','JKL','MNO'],       
'Groups': ['Group A', 'Group B', 'Group C','Group B', 'Group A']})

df3 = df3.merge(df2, on=['Code'])
df3.groupby(['Groups']).sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM