Home > database >  multiply values from two different dataframes
multiply values from two different dataframes

Time:11-26

I have two dataframes:

number 1

word weight
book 0.2
water 0.5

number two

description book water
xyz 1 0
abc 0 1

I would like to simply multiply each word weight with the values in the second dataframe and paste them in the second dataframe - instead of 1/0

CodePudding user response:

If match columns names in df2 without description with column df1.word you can use:

df = df2.set_index('description').mul(df1.set_index('word')['weight']).reset_index()
print (df)
  description  book  water
0         xyz   0.2    0.0
1         abc   0.0    0.5

Or if need multiple only matched columns use:

m = df2.columns.isin(df1['word'])
df2.loc[:, m] = df2.loc[:, m].mul(df1.set_index('word')['weight'])
print (df2)
  description  book  water
0         xyz   0.2    0.0
1         abc   0.0    0.5
  • Related