Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying pandas dataframe and series, element wise

Tags:

python

pandas

Lets say I have a pandas series:

import pandas as pd
x = pd.DataFrame({0: [1,2,3], 1: [4,5,6], 2: [7,8,9] })
y = pd.Series([-1, 1, -1])

I want to multiply x and y in such a way that I get z:

z = pd.DataFrame({0: [-1,2,-3], 1: [-4,5,-6], 2: [-7,8,-9] })

In other words, if element j of the series is -1, then all elements of the j-th row of x get multiplied by -1. If element k of the series is 1, then all elements of the j-th row of x get multiplied by 1.

How do I do this?

like image 787
wwl Avatar asked Oct 09 '16 21:10

wwl


People also ask

How do you do element wise multiplication in pandas?

mul() does an elementwise multiplication of a DataFrame with another DataFrame, a pandas Series or a Python Sequence. Calling the mul() method is similar to using the binary multiplication operator(*). The mul() method provides a parameter fill_value using which values can be passed to replace the np.

How do you multiply all values in a data frame?

The 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 I multiply all columns in pandas?

How do you multiply columns in a data frame? Use DataFrame indexing to multiply two columns Use the syntax df[col1] * df[col2] to multiply columns with names col1 and col2 in df . Use DataFrame indexing to assign the result to a new column.


1 Answers

You can do that:

>>> new_x = x.mul(y, axis=0)
>>> new_x
   0  1  2
0 -1 -4 -7
1  2  5  8
2 -3 -6 -9
like image 107
coder Avatar answered Oct 02 '22 14:10

coder