1

I want to multiply a list of columns with one col so I have list of the columns = cols and I want to multiply them with the columns "multi"

data={"col1":[2,3,4,5],
"col2":[4,2,4,6],
"col3":[7,6,9,11],
"col4":[14,11,22,8],
"multi":[1.4,2.5,1.6,2.2]}
df=pd.DataFrame.from_dict(data)
cols=list(df.columns)
cols.remove("multi")
df

So I try to do this:

df[cols]=df[cols]*df["multi"]

But I get

ValueError: Columns must be same length as key

Dharman
  • 30,962
  • 25
  • 85
  • 135
matan
  • 451
  • 4
  • 12
  • You could do `df.filter(like="col").multiply(df["multi"], 0)` instead of assigning the col names as a variable. – Henry Yik Aug 09 '20 at 11:03

4 Answers4

3
In [46]: data={"col1":[2,3,4,5],
    ...: "col2":[4,2,4,6],
    ...: "col3":[7,6,9,11],
    ...: "col4":[14,11,22,8],
    ...: "multi":[1.4,2.5,1.6,2.2]}
    ...: df=pd.DataFrame.from_dict(data)
    ...: cols=list(df.columns)
    ...: cols.remove("multi")
    ...: df
Out[46]:
   col1  col2  col3  col4  multi
0     2     4     7    14    1.4
1     3     2     6    11    2.5
2     4     4     9    22    1.6
3     5     6    11     8    2.2

In [47]: df[['col1','col2','col3','col4']].multiply(df["multi"], axis="index")
Out[47]:
   col1  col2  col3  col4
0   2.8   5.6   9.8  19.6
1   7.5   5.0  15.0  27.5
2   6.4   6.4  14.4  35.2
3  11.0  13.2  24.2  17.6
bigbounty
  • 16,526
  • 5
  • 37
  • 65
1
df[cols] = (df[cols].T*df["multi"]).T
PSK
  • 347
  • 2
  • 13
0

Try this:

df.iloc[:, your_cols] *= df['multi']

Where:

your_cols = [df.columns.get_loc(c) for c in cols]
Dor
  • 176
  • 1
  • 5
  • i get this: IndexError: .iloc requires numeric indexers, got ['col1' 'col2' 'col3' 'col4'] – matan Aug 09 '20 at 08:29
0

you can also try this

df.apply(lambda x :x[cols]*x["multi"], axis=1)
Dharman
  • 30,962
  • 25
  • 85
  • 135