Find values from a column in a DF at very specific times for every unique date

夙愿已清 提交于 2021-01-28 20:01:47

问题


I asked this question and I got an answer which works for a general case with sequential and non missing data but not for my case specifically. I have a DF that looks as follows.

eventTime       MeteredEnergy Demand RunningHoursLamps 
6/7/2018 0:00   67.728           64  1037.82
6/7/2018 1:00   67.793           64  1038.82
6/7/2018 2:00   67.857           64  1039.82
6/7/2018 3:00   67.922           64  1040.82
6/7/2018 4:00   67.987           64  1041.82
6/7/2018 5:00                    64  1042.82
6/7/2018 6:00                        1043.43
6/7/2018 23:00  68.288
6/8/2018 0:00   67.728           64  1037.82
6/8/2018 23:00  67.793           64  1097.82

I need a DF that finds the difference between RunningHoursLamps values at hour 0 and hour 23 for each unique date in "eventTime" If data is missing for hour 0 or hour 23, the resultant DF can have NaN

Expected output

    Date        00:00       23:00       Difference 
    6/7/2018    1037.82     NaN         NaN
    6/8/2018    1037.82     1097.82     60

回答1:


Update: For those that are interested: I found a way to do this. I parsed out a separate column with dates and hours from the eventTime column and looped through it and handled exceptions when I did not have data for the required DateTime. Thanks.

#for loop to build the bill dataframe
bill = pd.DataFrame()

for i in range(len(unique_dates)):
    try :
        if i == 0:
            hour0 = np.nan
        else:
            hour0 = df.loc[((df['date'] == unique_dates[i]) & (df['hour'] == 0)),'RunningHoursLamp'].values[0]
    except IndexError:
        hour0 = np.nan

    try :
        hour24 = df.loc[((df['date'] == unique_dates[i+1]) & (df['hour'] == 0)),'RunningHoursLamp'].values[0]
    except IndexError:
        hour24 = np.nan

    temp = pd.DataFrame([[unique_dates[i],hour0,hour24]],columns=['Date','Hour_0','Hour_24'])  
    bill = bill.append(temp,ignore_index=True)

bill


来源:https://stackoverflow.com/questions/60709492/find-values-from-a-column-in-a-df-at-very-specific-times-for-every-unique-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!