Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply each row in pandas dataframe by a different value

Tags:

python

pandas

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.

like image 626
johnchase Avatar asked Jun 29 '16 16:06

johnchase


People also ask

How do you multiply 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 pandas multiply values?

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.

How do you multiply a data frame by another DataFrame?

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.

How does pandas calculate row difference?

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.


1 Answers

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
like image 134
ayhan Avatar answered Oct 06 '22 02:10

ayhan