Eduardo Sahione
Eduardo Sahione

Reputation: 111

Multiplying Columns by Scalars in Pandas

Suppose I have a pandas DataFrame with two columns named 'A' and 'B'.

Now suppose I also have a dictionary with keys 'A' and 'B', and the dictionary points to a scalar. That is, dict['A'] = 1.2 and similarly for 'B'.

Is there a simple way to multiply each column of the DataFrame by these scalars?

Cheers!

Upvotes: 4

Views: 10415

Answers (2)

Wes McKinney
Wes McKinney

Reputation: 105551

As Wouter said, the recommended method is to convert the dict to a pandas.Series and multiple the two objects together:

result = df * pd.Series(myDict)

Upvotes: 5

BrenBarn
BrenBarn

Reputation: 251408

You could do:

for col in df.columns:
     df[col] *= myDict[col]

Upvotes: 1

Related Questions