pandas 计算不同开始和结束时间之间的平均值

uinbv5nw  于 2023-04-10  发布在  其他
关注(0)|答案(1)|浏览(115)

给定一个开始时间“T_S”和结束时间“T_E”的 Dataframe df,我想计算这些时间之间每行df的另一个Pandas Dataframe 的值Q的平均值。

df=pandas.DataFrame({'T_S':[30-09-2022  14:11:36, 30-09-2022  14:14:52, 30-09-2022  14:18:30],'T_E':[30-09-2022  14:14:22, 30-09-2022  14:18:20, 30-09-2022  14:21:11]})

计算Q值平均值的数据表如下所示:

dQ=pandas.DataFrame({'T':[2022-09-29 15:37:03, 2022-09-29 15:37:04  ,2022-09-29 15:37:05], 'Q':[1,5,6]})

我已经尝试了几个代码与between_time和group_by,但它抛出错误的每一次。我想我是卡住了一些简单的,但找不到出路。
任何帮助,请;)
谢啦

zhte4eai

zhte4eai1#

Blockquote
将pandas导入为pd

## Create a sample time-value table (dQ in your case)
dQ = pd.DataFrame({'time': [1, 2, 3, 4, 5],
               'value': [10.5, 20.3, 15.8, 18.6, 22.1]})

## Create a sample time1-time2 table (df in your case)
time_ranges = pd.DataFrame({'time1': [2, 4],
                        'time2': [3, 5]})

## Join the two tables based on the time column
merged_dQ = pd.merge(dQ, time_ranges, how='inner', on='time')

## Filter the rows where time is between time1 and time2
filtered_dQ = merged_dQ[(merged_dQ['time'] >= merged_dQ['time1']) & (merged_dQ['time'] <= merged_dQ['time2'])]

## Calculate the average of the values in the filtered table
avg_value = filtered_dQ['value'].mean()

print(avg_value)

相关问题