Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply all rows in a Pandas DataFrame by dictionary

Tags:

python

pandas

Say I have a DataFrame call it one like this:

non_multiply_col col_1 col_2
A Name           1     3

and a dict like this call it two:

{'col_1': 4, 'col_2': 5}

is there a way that I can multiply all rows of one by the values in two for the columns as defined by two's keys so the result would be:

non_multiply_col col_1 col_2
A Name           4     15

I tried using multiply, but I'm not really looking to join on anything specific. Maybe I'm not understanding how to use multiply correctly.

Thanks

like image 887
gr1zzly be4r Avatar asked May 02 '17 00:05

gr1zzly be4r


1 Answers

mul/multiply works fine if the dictionary is converted to a Series:

d = {'col_1': 4, 'col_2': 5}

df.mul(pd.Series(d), axis=1)

#   col_1   col_2
#0      4      15

In case you have more columns in the data frame than the dictionary:

df = pd.DataFrame([{'col_1': 1, 'col_2': 3, 'col_3': 4}])   
d = {'col_1': 4, 'col_2': 5}

cols_to_update = d.keys()  # you might need cols_to_update = list(d.keys()) in python 3
# multiply the selected columns and update
df[cols_to_update] = df[cols_to_update].mul(pd.Series(d), axis=1)[cols_to_update]
df

    col_1   col_2   col_3
#0      4      15       4

I happen to find this work as well, not sure if there is any caveat about this usage:

df[d.keys()] *= pd.Series(d)
like image 113
Psidom Avatar answered Oct 10 '22 15:10

Psidom