Python 对 Pandas 数据框中的所有值求和的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38733477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to sum all values in a Pandas dataframe?
提问by Bill
I figured out these two methods. Is there a better one?
我想出了这两种方法。有没有更好的?
>>> import pandas as pd
>>> df = pd.DataFrame({'A': [5, 6, 7], 'B': [7, 8, 9]})
>>> print df.sum().sum()
42
>>> print df.values.sum()
42
Just want to make sure I'm not missing something more obvious.
只是想确保我没有遗漏更明显的东西。
回答by piRSquared
Updated for Pandas 0.24+
为 Pandas 0.24+ 更新
df.to_numpy().sum()
Prior to Pandas 0.24+
在 Pandas 0.24+ 之前
df.values
Is the underlying numpy array
是底层的numpy数组
df.values.sum()
Is the numpy sum method and is faster
是 numpy sum 方法并且速度更快
回答by Raven
Adding some numbers to support this:
添加一些数字来支持这一点:
import numpy as np, pandas as pd
import timeit
df = pd.DataFrame(np.arange(int(1e6)).reshape(500000, 2), columns=list("ab"))
def pandas_test():
return df['a'].sum()
def numpy_test():
return df['a'].to_numpy().sum()
timeit.timeit(numpy_test, number=1000) # 0.5032469799989485
timeit.timeit(pandas_test, number=1000) # 0.6035906639990571
So we get a 20% performance on my machine just for Series summations!
所以我们在我的机器上获得了 20% 的性能,仅用于系列求和!