Multiply all the columns in the Pandas framework together

Is it possible to multiply all columns in a Pandas.DataFrame together to get one value for each row in a DataFrame?

As an example, using

 df = pd.DataFrame(np.random.randn(5,3)*10) 

I want a new DataFrame df2 , where df2.ix[x,0] will have the value df.ix[x,0] * df.ix[x,1] * df.ix[x,2] .

However, I do not want to do this, how to use a loop to achieve this?

I found the df.mul(series, axis=1) function df.mul(series, axis=1) , but cannot find a way to use it for my purpose.

+6
source share
1 answer

You can use 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 can also apply np.prod , this was originally done, but usually, when available, direct methods are faster.

 >>> 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 
+13
source

Source: https://habr.com/ru/post/944457/


All Articles