Python教程:DataFrame数据中使用resample计算月线平均值

在pandas库中,DataFrame可以使用resample()方法来对时间序列数据进行重采样。重采样是将原始数据按照指定的频率进行重新组织,以便进行更细粒度的分析或转换。下面是一个示例,演示如何使用resample()方法:

# @Author : 小红牛
# 微信公众号:wdPython

首先,导入必要的库:

import pandas as pd  
import numpy as np

然后,创建一个示例DataFrame,其中包含按日期索引的时间序列数据:

date_rng = pd.date_range('2023-01-01', periods=100, freq='D')  
data = np.random.randn(len(date_rng))  
df = pd.DataFrame(data, columns=['Value'], index=date_rng)

现在,我们可以使用resample()方法来对DataFrame进行重采样。例如,如果我们想要将数据按月重新采样并计算每个月的平均值,可以这样做:

resampled = df.resample('M').mean()  
print(resampled)

在上面的代码中,'M’表示按月重采样,mean()表示计算每个采样窗口的平均值。默认情况下,resample()方法使用前向填充(ffill)对缺失值进行填充,如果想要使用其他填充方法,可以通过传递fillna()函数来实现。

除了计算平均值,还可以使用resample()方法执行其他聚合操作,如求和、计数、最小值、最大值等。例如,要计算每个月的总和:

resampled = df.resample('M').sum()  
print(resampled)

Python教程:DataFrame数据中使用resample计算月线平均值_第1张图片

你可能感兴趣的:(我的Python教程,python,pandas,Python教程)