Finding mean of dataframe values based on values from another dataframe

Viewed 41

So I'm trying to find the mean of values in dataframe 1 where the values of dataframe 2 are equal to 1. Is there an easy way to do this?

Example:

    Dataframe 1:
           product1 product2 product3
    user1   2         4          5
    user2   1         3          4
    user3   3         2          1
    
    Dataframe 2: 
            product1 product2 product3
    user1   0        1        0
    user2   1        0        1
    user3   0        0        1

So, I'd end up with taking a mean of these values:

    Mean Dataframe:
         product1  product2 product3
    user1          4
    user2 1                 4
    user3                   1

So the mean, naturally, would be 2.5 However, in my example, I have approx 3000 rows and 300 columns, so cannot just use .loc[column == x] as there are too many columns.

1 Answers

If there is same index and same columns values use DataFrame.where:

df3 = df1.where(df2.eq(1))
Related