简体   繁体   中英

How to subtract two dataframes , partial common indexes

I have two dataframes a1,a2 with the same columns and indexes , but with different rows .

a1:
    f     d         r   f
0   50.1  0 -1.374201  35
1   50.2  1  1.415697  29
2   70  3  0.233841  18
3   80  4  1.550599  30
4   90.2  5 -0.178370  63

a2:
    f     d         r   f
2   25  3  0.233841  18
3   95  4  1.550599  30

I want to subtract a1 from a2, so a3=a2-a1 ,

So I will received:

a3:
     f     d         r   f
2   -45  0  0  0
3   15  4  0  0

Thanks,

It's fairly simple, first you do simple substraction and you'll get a 5x4 DataFrame that will only have results in the rows with the same indices, others will be NaN . Then you drop NaN values:

a3 = a2-a1
a3.dropna(inplace=True)

I'm not sure why in your desired DataFrame you want d at index 3 to equal 4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM