Skip to content
Advertisement

Multiply pandas dataframe with a differently shaped dataframe based on condition

I have a pandas DataFrame (df_A) with this basic form:

JavaScript

Furthermore I have another DataFrame (df_B):

JavaScript

What I want to do is multiply the values of the second DataFrame with the values of the first, where the alt value is the same. I also do not want the d or e columns to be involved in the multiplication. So I want a DataFrame (df_C) like this:

JavaScript

I have tried a few thing unsuccessfully:

JavaScript

This just returns the original DataFrame (df_A). I know my approach is deeply flawed but I cannot think of any way to do this.

Advertisement

Answer

You can use a merge and in place multiplication:

JavaScript

output:

JavaScript

intermediate:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement