来自pandas数据框的几列总和 [英] Sum of several columns from a pandas dataframe
本文介绍了来自pandas数据框的几列总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以说我有下表:
In [2]: df = pd.DataFrame({'a': [1,2,3], 'b':[2,4,6], 'c':[1,1,1]})
In [3]: df
Out[3]:
a b c
0 1 2 1
1 2 4 1
2 3 6 1
我可以这样对a和b求和:
I can sum a and b that way:
In [4]: sum(df['a']) + sum(df['b'])
Out[4]: 18
但是,这对于较大的数据框不是很方便,在较大的数据框中,您必须将多个列加在一起.
However this is not very convenient for larger dataframe, where you have to sum multiple columns together.
是否有一种比较整洁的方式来汇总列(类似于下面的内容)?如果我想对整个DataFrame求和而不指定列怎么办?
Is there a neater way to sum columns (similar to the below)? What if I want to sum the entire DataFrame without specifying the columns?
In [4]: sum(df[['a', 'b']]) #that will not work!
Out[4]: 18
In [4]: sum(df) #that will not work!
Out[4]: 21
推荐答案
我认为您可以使用双精度sum
-首先 Series.sum
获得Series
的总和:
I think you can use double sum
- first DataFrame.sum
create Series
of sums and second Series.sum
get sum of Series
:
print (df[['a','b']].sum())
a 6
b 12
dtype: int64
print (df[['a','b']].sum().sum())
18
您还可以使用:
print (df[['a','b']].sum(axis=1))
0 3
1 6
2 9
dtype: int64
print (df[['a','b']].sum(axis=1).sum())
18
谢谢您 pirSquared 另一种解决方案-通过
Thank you pirSquared for another solution - convert df
to numpy array
by values
and then sum
:
print (df[['a','b']].values.sum())
18
print (df.sum().sum())
21
这篇关于来自pandas数据框的几列总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文