简体   繁体   中英

Scroll through two data frames and compare a column of data

I have the following dataframes:

      import pandas as pd
      import numpy as np

      df_Sensor = pd.DataFrame({'ID_System_Embed': ['1000', '1000', '1000', '1003', '1004'], 
                      'Date_Time': ['2020-10-18 12:58:05', '2020-10-18 12:58:15',
                                    '2020-10-19 20:10:10', '2018-12-18 12:58:00', 
                                    '2015-10-25 11:00:00']})



     df_Period = pd.DataFrame({'ID_System_Embed': ['1000', '1000', '1001', '1002', '1003', '1004'],
                      'ID_Sensor': ['1', '2', '3', '4', '5', '6'], 
                      'Date_Init': ['2020-10-18 12:58:00', '2020-10-18 19:58:00',
                                    '2019-11-18 19:58:00', '2018-12-29 12:58:00',
                                    '2019-11-20 12:58:00', '2015-10-25 10:00:00'],

                      'Date_End': ['2020-10-18 16:58:00', '2020-10-19 20:58:00',
                                   '2019-11-25 12:58:00', '2018-12-18 12:58:00',
                                   '2019-11-25 12:58:00', '2015-10-25 12:00:00']})

I need to detect if the date of the dataframe 'df_Sensor' is contained in the date range of the second dataframe (df_Period) for the same ID_System_Embed (Identifier of an embedded system).

I tried to implement the following code:

      df_Period['New_Column'] = 0

     for j in range(0, len(df_Period)):
          for i in range(0, len(df_Sensor)):


              if((df_Sensor['ID_System_Embed'].iloc[i] == df_Period['ID_System_Embed'].iloc[j]) &
                 (df_Sensor['Date_Time'].iloc[i] >= df_Period['Date_Init'].iloc[j]) &
                 (df_Sensor['Date_Time'].iloc[i] <= df_Period['Date_End'].iloc[j])):

                   df_Period['New_Column'].iloc[j] += 1       

This code is merging and is resulting in the expected output. However, it is not very effective because it needs to iterate between the two data frames (using for). I would like to discover a faster and more efficient way to do the operation and result in the same output.

The output is:

       ID_System_Embed     ID_Sensor       Date_Init          Date_End           New_Column
           1000               1       2020-10-18 12:58:00   2020-10-18 16:58:00     2
           1000               2       2020-10-18 19:58:00   2020-10-19 20:58:00     1
           1001               3       2019-11-18 19:58:00   2019-11-25 12:58:00     0
           1002               4       2018-12-29 12:58:00   2018-12-18 12:58:00     0
           1003               5       2019-11-20 12:58:00   2019-11-25 12:58:00     0
           1004               6       2015-10-25 10:00:00   2015-10-25 12:00:00     1

Group df_Period and df_Sensor by ['ID_System_Embed', 'ID_Sensor'] as unique keys
Then Aggregate values of other dates columns as a list using appnd function

def appnd(col):
    return [d for d in col]

df_p = df_Period.copy().groupby(['ID_System_Embed', 'ID_Sensor']).agg(appnd)
df_s = df_Sensor.copy().groupby(['ID_System_Embed']).agg(appnd)

Then join the two dataframes (you may fill NaN with 0)

df = df_p.join(df_s).fillna(value = 0)
df['New_Column'] = 0
df

在此处输入图片说明

Apply this function to the dates columns mapping results to New_Column

def inInterval(row):
    ctr = 0
    for d in row[2]:
        for start, end in zip(row[0], row[1]):
            if  start <= d <= end: ctr +=1
    return ctr

df['New_Column'] = df[ ['Date_Init', 'Date_End', 'Date_Time'] ].copy()\
                    .apply(lambda x: inInterval(x)  if type(x[2]) == list else 0, axis = 1)
df

在此处输入图片说明

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