Monica Monica - 3 months ago 7
Python Question

Substracting values from different DataFrame

I got two DataFrames and Want to substract.

df1:

Val1 Val2 Val3
0 -27 -0.8 -6.786321 -7.024615 -13.946589
1 -27 -0.9 -5.746795 -5.804550 -11.576365
2 -27 -1.0 -4.624857 -4.372321 -9.103681
3 -27 -1.2 -2.685832 -2.418888 -5.057056
4 -27 -1.4 -1.445561 -1.389468 -2.622357


df2:

Bench
0 0.4601
1 -5.3336
2 -6.0163
3 -4.1776
4 -2.3472


As I have the same indexes, I tried to do:
df1-df2
, but it didn't work.

Therefore I've tried to use another way:

headers = list(df1.columns.values)
filtr_headers = filter(lambda x: x!='',headers)
for i in filtr_headers:
df1['%s' %(i)] = df1['%s' %(i)] - df2['Bench']


But I'm getting in return Dataframe with NaN values. I don't know why it's happening. Any hints will be higly appreciated.

Answer

You can use pd.DataFrame.sub, like this:

In [113]: df1.sub(df2.Bench.values, axis=0)
Out[113]: 
                Val1      Val2       Val3
0 -27 -0.8 -7.246421 -7.484715 -14.406689
1 -27 -0.9 -0.413195 -0.470950  -6.242765
2 -27 -1.0  1.391443  1.643979  -3.087381
3 -27 -1.2  1.491768  1.758712  -0.879456
4 -27 -1.4  0.901639  0.957732  -0.275157