I am trying to multiply each row of a pandas dataframe by a different value and wondering what the best way to do this is.
For example if I have the following dataframe:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(2, 3))
df
0 1 2
0 -1.283316 0.849488 1.936060
1 -2.078575 -0.871570 -0.970261
I want to multiply each element of each row by a different in a list or array
vals = [1, 100]
In this example I want each item in the first row to be multiplied by 1 and each item in the second row to be multiplied by 100
the result should therefore be:
0 1 2
0 -1.283316 0.849488 1.936060
1 -207.8575 -87.1570 -97.0261
I have tried:
df * vals
df.multiply(vals)
df.multiply(vals, axis=1)
None of which work, although I was not expecting them too, based on my understanding of what that code should do. I can't figure out a concise way to do this with pandas, any help is appreciated, thanks.
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.
multiply() function perform the multiplication of series and other, element-wise. The operation is equivalent to series * other , but with support to substitute a fill_value for missing data in one of the inputs.
The mul() method of DataFrame object multiplies the elements of a DataFrame object with another DataFrame object, series or any other Python sequence. mul() does an elementwise multiplication of a DataFrame with another DataFrame, a pandas Series or a Python Sequence.
Difference between rows or columns of a pandas DataFrame object is found using the diff() method. The axis parameter decides whether difference to be calculated is between rows or between columns. When the periods parameter assumes positive values, difference is found by subtracting the previous row from the next row.
The method is mul
:
df.mul([1, 100], axis=0)
Out[17]:
0 1 2
0 -1.198766 -1.340028 1.990843
1 113.890468 -68.177755 -9.060228
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