Home > Mobile >  Finding the delta of two unmatched dataframes in pandas
Finding the delta of two unmatched dataframes in pandas

Time:09-27

Having 2 Data Frames with readings at 2 different times as:

DF1

       Sensor ID    Reference Pressure     Sensor Pressure
0         013677                100.15               93.18
1         013688                101.10               95.23
2         013699                100.87               93.77
...          ...                  ...                  ...

And

DF2

       Sensor ID    Reference Pressure     Sensor Pressure
0         013688                120.01              119.43
1         013677                118.93              118.88
2         013699                120.05              118.85
...          ...                  ...                  ...

What would be the optimal way of creating a third Dataframe, that contains the difference between those readings, given that the "Sensor ID" values order does not match between the two dataframes?

CodePudding user response:

Pandas has this beautiful feature where it automatically aligns on indices. So we can use that to solve your problem:

df1.set_index("Sensor ID").sub(df2.set_index("Sensor ID"))
           Reference Pressure  Sensor Pressure
Sensor ID                                     
13677                  -18.78           -25.70
13688                  -18.91           -24.20
13699                  -19.18           -25.08
  • Related