Pandas : Sum multiple columns and get results in multiple columns

断了今生、忘了曾经 提交于 2019-12-01 01:08:31
piRSquared

When you pass a dictionary or callable to groupby it gets applied to an axis. I specified axis one which is columns.

d = dict(A='AB', B='AB', C='CD', D='CD')
df.groupby(d, axis=1).sum()

Use concat with sum:

df = df.set_index('idx')
df = pd.concat([df[['A', 'B']].sum(1), df[['C', 'D']].sum(1)], axis=1, keys=['AB','CD'])
print( df)
     AB  CD
idx        
J     3   4
K     9   8
L    15  12
M     3   7
N     9  11
O    15  15

Does this do what you need? By using axis=1 with DataFrame.apply, you can use the data that you want in a row to construct a new column. Then you can drop the columns that you don't want anymore.

In [1]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A', 'B', 'C', 'D'], data=[[1, 2, 3, 4], [1, 2, 3, 4]])

In [6]: df
Out[6]:
   A  B  C  D
0  1  2  3  4
1  1  2  3  4

In [7]: df['CD'] = df.apply(lambda x: x['C'] + x['D'], axis=1)

In [8]: df
Out[8]:
   A  B  C  D  CD
0  1  2  3  4   7
1  1  2  3  4   7

In [13]: df.drop(['C', 'D'], axis=1)
Out[13]:
   A  B  CD
0  1  2   7
1  1  2   7
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!