Skip to content
Advertisement

How to multiply all numerical columns of a dataframe by a one-dimensional array?

I have a dataframe df of shape r x c, with 1 text column (with non-unique values) and the other columns all floats. I then have an array mult of size r. I would like each numerical column of the dataframe to be multiplied by the corresponding item of the array.

Ie the desired output is that value_1[0] should become value_1[0] * mult[0], value_2[0] should become value_2[0] * mult[0], etc.

What is an easy way to do it?

I have tried the code below but it doesn’t work.

import numpy as np
import pandas as pd

df = pd.DataFrame()

df['txt']=['a','b','c','a','d']
df['value_1'] = np.arange(0,5)
df['value_2'] = np.arange(10,15)

mult = np.array([1,1,0,0,1])

newdf = df * mult

newdf2 = df.set_index('txt') * np.array

Advertisement

Answer

In [1689]: x = df.select_dtypes(int).columns

In [1690]: df[x] = df.select_dtypes('int').mul(mult, axis=0)

In [1691]: df
Out[1691]: 
  txt  value_1  value_2
0   a        0       10
1   b        1       11
2   c        0        0
3   a        0        0
4   d        4       14
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement