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.
JavaScript
x
15
15
1
import numpy as np
2
import pandas as pd
3
4
df = pd.DataFrame()
5
6
df['txt']=['a','b','c','a','d']
7
df['value_1'] = np.arange(0,5)
8
df['value_2'] = np.arange(10,15)
9
10
mult = np.array([1,1,0,0,1])
11
12
newdf = df * mult
13
14
newdf2 = df.set_index('txt') * np.array
15
Advertisement
Answer
JavaScript
1
13
13
1
In [1689]: x = df.select_dtypes(int).columns
2
3
In [1690]: df[x] = df.select_dtypes('int').mul(mult, axis=0)
4
5
In [1691]: df
6
Out[1691]:
7
txt value_1 value_2
8
0 a 0 10
9
1 b 1 11
10
2 c 0 0
11
3 a 0 0
12
4 d 4 14
13