1

I have the following dataframe and data list, respectively:

      import pandas as pd

      df = pd.DataFrame({'ID': [1, 2, 4, 7, 30], 
                         'Instrument': ['temp_sensor', 'temp_sensor', 'temp_sensor',
                                        'strain_gauge', 'light_sensor'],
                         'Value': [1000, 0, 1000, 0, 1000]})

      print(df)


     ID      Instrument     Value
     1     temp_sensor     1000
     2     temp_sensor      0
     4     temp_sensor     1000
     7     strain_gauge    0
     30    light_sensor   1000


     list_ID = [2, 30]

I would like to generate a new dataframe that corresponds to the dataframe df, but that it would receive only the lines where the ID belongs to list_ID.

I tried to implement the following code. However, it is not working:

      d = {'ID':[], 'Instrument':[], 'Value':[]}

      df_aux = pd.DataFrame(d)

      for j in range(0, len(df)):
           for k in range(0, len(list_ID)):
    
               if(df['ID'][j] == list_ID[k]):
        
               df_aux.append(df[df['ID'][j] == list_ID[k]])

The error appears: KeyError: True

I would like the output of df_aux to be:

       ID       Instrument     Value
        2       temp_sensor       0
       30       light_sensor    1000
Jane Borges
  • 552
  • 5
  • 14

0 Answers0