Home > Software engineering >  How to divide two dataframes elementwise
How to divide two dataframes elementwise

Time:11-03

I have two dataframes, they share the same columns and one has more indexes than the other, what I want is to divide each element of one dataframe by the corresponding element (having the same index and column) in another dataframe, an example:

df1

    value1              value2                  
0     1                   3            
1     2                   4  
2     5                   6  

df2

    value1              value2                  
0     2                   2            
1     2                   2    

The result would be:

    value1              value2                  
0     0.5                 1.5            
1     1                   2    

Also in my real example, the indexes are not ordered as here (they are dates).

CodePudding user response:

If no missing values in original DataFrame remove only NaNs rows after division:

df = df1.div(df2).dropna(how='all')
print (df)
   value1  value2
0     0.5     1.5
1     1.0     2.0

Or first filter common indices in DataFrame.loc with Index.intersection:

common = df1.index.intersection(df2.index)
df = df1.loc[common].div(df2.loc[common])
print (df)
   value1  value2
0     0.5     1.5
1     1.0     2.0

If need also filter common columns names:

common_idx = df1.index.intersection(df2.index)
common_cols = df1.columns.intersection(df2.columns)

df = df1.loc[common_idx, common_cols].div(df2.loc[common_idx, common_cols])
  • Related