Reputation: 13715
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.
Upvotes: 25
Views: 43564
Reputation: 23171
The most pandastic way is mul
on axis=0
. That said, to make *
work, we need a column array where the number of rows match the number of rows of the frame. So the following work.
vals = np.array([1, 100])
df1 = df * vals[:, None]
# or to modify the original frame
df *= vals[:, None]
Upvotes: 1
Reputation:
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
Upvotes: 30