Calculate the oscillation of two dataframes

Viewed 76

I have two dataframes. One represents the minimum values ​​and the other the maximum values. As below:

      df_Min = pd.DataFrame({'IDsensor': [1, 2, 3], 
                            'Sensor_SYS1_Min': [54, 55, 75],
                            'Sensor_SYS2_Min': [320, 315, 400]})


      df_Max = pd.DataFrame({'IDsensor': [1, 2, 3], 
                             'Sensor_SYS1_Max': [55, 60, 80],
                             'Sensor_SYS2_Max': [320, 320, 800]})

I would like to calculate the variation between them. That is, the oscillation between the maximum value and the minimum value.

I tried to do the following operation (This operation is incorrect):

      df_Oscillation = abs(df_Max - df_Min) 

I would like the output to be like this:

      df_Oscillation = pd.DataFrame({'IDsensor': [1, 2, 3], 
                                     'Sensor_SYS1_Oscillation': [1, 5, 5],
                                     'Sensor_Oscillation': [0, 5, 400]})
2 Answers

Two key changes: use an index and use the abs method

df_Min.set_index('IDsensor', inplace=True)
df_Max.set_index('IDsensor', inplace=True)

(df_Max - df_Min).abs()

Setting the index like this allows the dataframes to align on the sensor id for subtraction even if they are created with the IDs in different orders. Using the .abs method allows operations to be handled efficiently over the dataframe.

This worked when I tried it: abs(df_Max.subtract(df_Min))
This also worked: df_Max.subtract(df_Min).abs()

import pandas as pd
df_Min = pd.DataFrame({'IDsensor': [1, 2, 3], 
                      'Sensor_SYS1': [54, 55, 75],
                      'Sensor_SYS2': [320, 315, 400]})

df_Max = pd.DataFrame({'IDsensor': [1, 2, 3], 
                        'Sensor_SYS1': [55, 60, 80],
                        'Sensor_SYS2': [320, 320, 800]})

def print_df(title, df):
  return print(f'{title}\n{df}\n')

print_df('df_Min', df_Min)
print_df('df_Max', df_Max)
print_df('df_Oscillation', df_Max.subtract(df_Min).abs())
Related