pandas :给定列的总和DataFrame行 [英] Pandas: sum DataFrame rows for given columns
本文介绍了 pandas :给定列的总和DataFrame行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下DataFrame:
I have the following DataFrame:
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
我想添加一列'e',这是列'a ','b'和'd'。
I would like to add a column 'e' which is the sum of column 'a', 'b' and 'd'.
跨论坛,我以为这样会有效:
Going across forums, I thought something like this would work:
df['e'] = df[['a','b','d']].map(sum)
但不是!
我想实现具有列列表 ['a','b','d']
和 df
作为输入。
I would like to realize the operation having the list of columns ['a','b','d']
and df
as inputs.
推荐答案
您可以 sum
并设置参数 axis = 1
总结行,这将忽略无数字列:
You can just sum
and set param axis=1
to sum the rows, this will ignore none numeric columns:
In [91]:
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
a b c d e
0 1 2 dd 5 8
1 2 3 ee 9 14
2 3 4 ff 1 8
如果您只想对特定列进行总结,那么您可以创建一个列列表,并删除不感兴趣的列:
If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:
In [98]:
col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:
df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
a b c d e
0 1 2 dd 5 3
1 2 3 ee 9 5
2 3 4 ff 1 7
这篇关于 pandas :给定列的总和DataFrame行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文