将 Pandas 数据框中的所有列相乘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16423736/
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
Multiply all columns in a Pandas dataframe together
提问by Nyxynyx
Is it possible to multiply all the columns in a Pandas.DataFrametogether to get a single value for every row in the DataFrame?
是否可以将 a 中的所有列相乘Pandas.DataFrame以获得 DataFrame 中每一行的单个值?
As an example, using
例如,使用
df = pd.DataFrame(np.random.randn(5,3)*10)
I want a new DataFramedf2where df2.ix[x,0]will have the value of df.ix[x,0] * df.ix[x,1] * df.ix[x,2].
我想要一个新的DataFramedf2wheredf2.ix[x,0]值df.ix[x,0] * df.ix[x,1] * df.ix[x,2].
However I do not want to hardcode this, how can I use a loop to achieve this?
但是我不想对此进行硬编码,如何使用循环来实现这一点?
I found a function df.mul(series, axis=1)but cant figure out a way to use this for my purpose.
我找到了一个函数,df.mul(series, axis=1)但无法想出一种方法来将它用于我的目的。
回答by DSM
You could use DataFrame.prod():
你可以使用DataFrame.prod():
>>> df = pd.DataFrame(np.random.randint(1, 10, (5, 3)))
>>> df
0 1 2
0 7 7 5
1 1 8 6
2 4 8 4
3 2 9 5
4 3 8 7
>>> df.prod(axis=1)
0 245
1 48
2 128
3 90
4 168
dtype: int64
You could also applynp.prod, which is what I'd originally done, but usually when available the direct methods are faster.
你也可以applynp.prod,这是我最初所做的,但通常直接方法可用时更快。
>>> df = pd.DataFrame(np.random.randint(1, 10, (5, 3)))
>>> df
0 1 2
0 9 3 3
1 8 5 4
2 3 6 7
3 9 8 5
4 7 1 2
>>> df.apply(np.prod, axis=1)
0 81
1 160
2 126
3 360
4 14
dtype: int64

