Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply all columns in a Pandas dataframe together

Is it possible to multiply all the columns in a Pandas.DataFrame together to get a single value for every row in the 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 of 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.

like image 587
Nyxynyx Avatar asked May 07 '13 16:05

Nyxynyx


People also ask

How do I multiply Panda DataFrame?

Pandas DataFrame mul() MethodThe mul() method multiplies each value in the DataFrame with a specified value. The specified value must be an object that can be multiplied with the values of the DataFrame.

How do you multiply Series in pandas?

Get Multiplication of series in PandasThe mul() function is used to get Multiplication of series and other, element-wise (binary operator mul). Equivalent to series * other, but with support to substitute a fill_value for missing data in one of the inputs.


1 Answers

You could 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 could also apply np.prod, which is what I'd originally done, but usually when available the 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
like image 184
DSM Avatar answered Oct 08 '22 10:10

DSM