Python熊猫,在填写调查前计算15分钟的平均温度传感器(匹配时间戳+添加新列)

我正在尝试在由调查数据(= PIT_da.xlsx)组成的Excel后面添加新列。在这些栏中,应计算并添加调查前15、30和60分钟的平均传感器值(例如温度)。传感器数据位于excel文件“ IEQ_da.xlsx”(包括时间戳)中。

我开始是这样的:

#import raw file
import pandas as pd
import numpy as np
dfSD = pd.read_excel('IEQ_da.xlsx')
dfPIT = pd.read_excel('PIT_da.xlsx')

#main aim: add after each survey result row in PIT_da.xlsx columns for the average values of the indoor environmental quality parameters in 15/30/60 minutes before submitting the survey

#Step 0: set both timestamp and submitdate to right datetime object
dfSD['timestamp'] =  pd.to_datetime(dfSD['timestamp'], format='%d%b%Y:%H:%M:%S.%f')
dfPIT['submitdate'] =  pd.to_datetime(dfPIT['submitdate'], format='%d%b%Y:%H:%M:%S.%f')

#Step 1: introduce arrays and set to numpy
array1 = dfSD[['timestamp']].to_numpy().ravel()
array2 = dfPIT[['submitdate']].to_numpy().ravel()
data_sensorID = dfSD[['devid']].to_numpy().ravel()
survey_sensorID = dfPIT[['PIT5']].to_numpy().ravel()Each survey has a timestamp (=submitdate) and should be matched to the sensor data at that timestamp. 

时间转换成数字就可以计算出15min / 30min / 60min之差

#Step 2: set timestamps to number and define a match 
from datetime import datetime
def timestamps(x) : 
    Timestamps = np.empty(x.size)
    for i in range(x.size) : 
        date = x[i]
        dt64 = np.datetime64(date)
        timestamp = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
        Timestamps[i] = timestamp
    return Timestamps

array1TS = timestamps(array1)
array2TS = timestamps(array2)

接下来,对每个调查提交时间和传感器时间戳(已经四舍五入到最接近的5分钟)进行匹配,包括来自相同传感器设备ID(= devid)和PIT5(调查中询问了传感器ID的传感器的问题)的条件。附近的传感器)。

#Step 3: define match with conditions: must be same timestamp and must have same sensor ID, by means of a matrix
Match = np.empty([array1TS.size, array2TS.size])
for i in range(array1TS.size) : 
    for j in range(array2TS.size):
        if (data_sensorID[i] == survey_sensorID[j]):
            if (array1TS[i] == array2TS[j]):
                Match[i,j] = 1;
            else: 
                Match[i,j] = 0;

现在,通过此匹配,应将新列添加到“ PIT_da.xlsx”,其平均值为在IEQ_da.xlsx文件中带有温度值的列“ SENtemp”的匹配时间戳记之前15分钟。

问题: 1.如何从“匹配”转到匹配时间戳之前15分钟的该时间戳中的所有行。 2.如何计算这些选定行的平均值(忽略空单元格)并将其放置在PIT_da.xlsx中的新列中(此新列应命名为“ SENtemp_15”),用于填充调查前15分钟内的温度在)。

作为参考,使用了一些数据行:

IEQ_da.xlsx

    import pandas as pd

df = pd.DataFrame({'timestamp' : ['14/04/2020  00:18:00', '14/04/2020  00:18:05', '14/04/2020  00:17:55', '14/04/2020  00:17:50' , '14/04/2020  00:17:40', '14/04/2020  00:17:40', '14/04/2020  00:17:20', '14/04/2020  00:17:20'], 'devid' : ['4', '2', '4', '2', '4' , '2' , '4' , '2'], 
                       'SENtemp' : ['20,2', '18,8', '20,1', '19', '20,2', '18,8', '20,1', '18,9']})
df

PIT_da.xlsx

import pandas as pd

df = pd.DataFrame({'submitdate' : ['14/04/2020  00:18:00', '14/04/2020  00:18:05'], 'PIT5' : ['4', '2'],
                   })
df

我希望有人愿意帮助我!

评论
22相亲
22相亲

Your 2 initial steps are rather useless. You can directly use apply on dfPIT to build the new column(s). The hardest part is that SENtemp is a string column with comma as decimal point which cannot be directly converted into float. Possible code:

delta = [15, 30, 60]  # delta in minutes

columns = [f'Average{i}' for i in delta]  # column names per delta values

dfPIT[columns] = dfPIT.apply(axis=1, func=lambda x: pd.Series(
    [dfSD.loc[(dfSD['timestamp']>x['submitdate'] - pd.Timedelta(i, 'T'))
              &(dfSD['timestamp']<=x['submitdate']), 'SENtemp']
     .str.replace(',','.').astype('float').mean() for i in delta],
    index=columns))

利用您的样本数据,它可以提供:

           submitdate PIT5  Average15  Average30  Average60
0 2020-04-14 00:18:00    4  19.614286  19.614286  19.614286
1 2020-04-14 00:18:05    2  19.512500  19.512500  19.512500
点赞
评论