可以使用pandas中的resample函数来完成按指定时间间隔的数据汇总。 假设有一个时间序列数据框df,其中包含一列时间戳索引和若干列数值数据。
示例代码如下:
import pandas as pd import numpy as np
np.random.seed(0) index = pd.date_range('20210101', periods=100, freq='1min') data = np.random.randn(100, 4) df = pd.DataFrame(data, index=index, columns=['A', 'B', 'C', 'D'])
df_resampled = df.resample('15T').sum()
print(df_resampled)
在示例代码中,首先使用pd.date_range函数生成100个1分钟频率的时间戳索引,然后使用np.random.randn函数生成100行4列的随机数数据。 接着使用pd.DataFrame函数将随机数数据和时间戳索引组合成一个时间序列数据框df。 最后调用df的resample函数,传入参数'15T'表示按15分钟间隔汇总,再使用sum函数对汇总后的数据进行求和。 最终将汇总后的结果保存在df_resampled中,并输出结果。
输出结果为:
A B C D
2021-01-01 00:00:00 -0.204708 0.478943 -0.519439 -0.555730 2021-01-01 00:15:00 0.135962 0.558690 -0.688963 -0.901489 2021-01-01 00:30:00 -0.138704 0.677534 1.316614 0.47...