Python数据分析:时间数据重采样
·
Python数据分析:时间数据重采样
重采样:
-
将时间序列从一个频率转换到另一个频率得的过程,需要聚合
-
高频率转换为低频率,downsampling,相反的过程为upsampling
-
pandas中的resample方法实现重采样
-
产生resample对象
import pandas as pd import numpy as np date_rng = pd.date_range('20190101', periods=60, freq='D') ser_obj = pd.Series(range(len(date_rng)), index=date_rng) print(ser_obj.head(10))运行:

-
resample(freq).sum(), resample(freq).mean(),……
# 统计每个月的数据总和 resample_month_sum = ser_obj.resample('M').sum() # 统计每个月的数据平均 resample_month_mean = ser_obj.resample('M').mean() print('按月求和:', resample_month_sum) print('按月求均值:', resample_month_mean)运行:

-
降采样(downsampling):
-
将数据聚合到规整的低频率
# 将数据聚合到5天的频率 five_day_sum_sample = ser_obj.resample('5D').sum() print('降采样,sum') print(five_day_sum_sample)运行:

-
OHLC重采样,open, high, low, close
five_day_ohlc_sample = ser_obj.resample('5D').ohlc() print('降采样,ohlc') print(five_day_ohlc_sample)运行:

-
使用groupby降采样
# 使用groupby降采样 print(ser_obj.groupby(lambda x: x.month).sum())运行:

升采样:
df = pd.DataFrame(np.random.randn(5, 3),
index=pd.date_range('20190301', periods=5, freq='W-MON'),
columns=['S1', 'S2', 'S3'])
print(df)
运行:

-
将数据从低频率转换到高频率,需要插值,否则为NaN
# 直接重采样会产生空值 print(df.resample('D').asfreq())运行:

-
常用插值方法:
-
ffill(limit), 空值区前面的值填充,limit为填充个数
#ffill print(df.resample('D').ffill(2))运行:

-
bfill(limit), 空值取后面的值填充
print(df.resample('D').bfill())运行:

-
fillna(‘ffill’) 或 fillna(‘bfill’)
print(df.resample('D').fillna('ffill'))运行:

-
interpolate, 根据插值算法补全数据
print(df.resample('D').interpolate('linear'))运行:

-
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)