That's actually a job for mask
or where
.
df2.mask(df1 <= df2, df2 - df1)
Or,
df2.where(df1 > df2, df2 - df1)
More generally, this is from numpy:
np.where(df1 > df2, df2, df2 - df1)
For these sample DataFrames:
df1
Out:
A B C
0 0.446762 -0.435975 0.109038
1 -0.729108 3.670354 0.761667
2 -0.244370 -0.256956 -1.831161
df2
Out:
A B C
0 -1.192108 0.074628 -0.087634
1 -0.324098 0.698479 -0.287896
2 1.807863 -2.564992 -2.361296
The first two yield
A B C
0 -1.192108 0.510603 -0.087634
1 0.405010 0.698479 -0.287896
2 2.052233 -2.564992 -2.361296
np.where
returns a numpy array so you might need to convert it back to a DataFrame:
array([[-1.19210755, 0.51060284, -0.08763422],
[ 0.40500973, 0.69847936, -0.28789618],
[ 2.05223294, -2.56499239, -2.36129577]])