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?
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.
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With