如果在某些时间/值之间,熊猫累积总和

tho*_*hor 5 python loops cumulative-sum pandas

我想插入一个名为新列totalfinal_df其中是的累加值valuedf,如果在时间之间发生时final_df。如果它出现在startendin之间,它就会对这些值求和final_df。因此,例如在 01:30 到 02:00 的时间范围内final_df- 索引 0 和 1 都df发生在此时间范围之间,因此总数为 15 (10+5)。

我有两个熊猫数据框:

df

import pandas as pd

d = {'start_time': ['01:00','00:00','00:30','02:00'], 
     'end_time': ['02:00','03:00','01:30','02:30'], 
     'value': ['10','5','20','5']}

df = pd.DataFrame(data=d)
Run Code Online (Sandbox Code Playgroud)

final_df

final_df = {'start_time': ['00:00, 00:30, 01:00, 01:30, 02:00, 02:30'],
            'end_time': ['00:30, 01:00, 01:30, 02:00, 02:30, 03:00']}

final_df = pd.DataFrame(data=final_d)
Run Code Online (Sandbox Code Playgroud)

输出我想要 final_df

start_time  end_time total
00:00       00:30    5
00:30       01:00    25
01:00       01:30    35
01:30       02:00    15
02:30       03:00    10
Run Code Online (Sandbox Code Playgroud)

我的尝试

final_df['total'] = final_df.apply(lambda x: df.loc[(df['start_time'] >= x.start_time) & 
                                            (df['end_time'] <= x.end_time), 'value'].sum(), axis=1)
Run Code Online (Sandbox Code Playgroud)

问题一

我收到错误:TypeError: ("'>=' not supported between 'str' and 'datetime.time'", 'occurred at index 0')

我将相关列转换为日期时间,如下所示:

df[['start_time','end_time']] = df[['start_time','end_time']].apply(pd.to_datetime, format='%H:%M')
final_df[['start_time','end_time']] = final_df[['start_time','end_time']].apply(pd.to_datetime, format='%H:%M:%S')
Run Code Online (Sandbox Code Playgroud)

但我不想转换为日期时间。有没有解决的办法?

问题二

总和工作不正常。它只是寻找时间范围的精确匹配。所以输出是:

 start_time  end_time total
    00:00       00:30    0
    00:30       01:00    0
    01:00       01:30    0
    01:30       02:00    0
    02:30       03:00    5
Run Code Online (Sandbox Code Playgroud)

Ben*_*n.T 3

一种不使用的方法apply可能是这样的。

df_ = (df.rename(columns={'start_time':1, 'end_time':-1}) #to use in the calculation later
         .rename_axis(columns='mult') # mostly for esthetic
         .set_index('value').stack() #reshape the data
         .reset_index(name='time') # put the index back to columns
      )
df_ = (df_.set_index(pd.to_datetime(df_['time'], format='%H:%M')) #to use resampling technic
          .assign(total=lambda x: x['value'].astype(float)*x['mult']) #get plus or minus the value depending start/end
          .resample('30T')[['total']].sum() # get the sum at the 30min bounds
          .cumsum() #cumulative sum from the beginning
      )
# create the column for merge with final resul
df_['start_time'] = df_.index.strftime('%H:%M')

# merge
final_df = final_df.merge(df_)
Run Code Online (Sandbox Code Playgroud)

你得到

print (final_df)
  start_time end_time  total
0      00:00    00:30    5.0
1      00:30    01:00   25.0
2      01:00    01:30   35.0
3      01:30    02:00   15.0
4      02:00    02:30   10.0
5      02:30    03:00    5.0
Run Code Online (Sandbox Code Playgroud)

但是如果你想使用 apply,首先你需要确保列是好的数据类型,然后你以相反的顺序执行不等式,如下所示:

df['start_time'] = pd.to_datetime(df['start_time'], format='%H:%M')
df['end_time'] = pd.to_datetime(df['end_time'], format='%H:%M')
df['value'] = df['value'].astype(float)
final_df['start_time'] = pd.to_datetime(final_df['start_time'], format='%H:%M')
final_df['end_time'] = pd.to_datetime(final_df['end_time'], format='%H:%M')

final_df.apply(
    lambda x: df.loc[(df['start_time'] <= x.start_time) & #see other inequality
                     (df['end_time'] >= x.end_time), 'value'].sum(), axis=1)
0     5.0
1    25.0
2    35.0
3    15.0
4    10.0
5     5.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)