python - 以最少的观察次数对 Pandas 进行重新采样

标签 python pandas resampling

我无法弄清楚如何对 pandas 日期时间索引数据框进行重采样,但需要最少数量的值才能给出一个值。我想将每日数据重新采样为每月,并且需要至少 90% 的值存在才能产生一个值。

输入每日数据:

import pandas as pd
rng = pd.date_range('1/1/2011', periods=365, freq='D')
ts = pd.Series(pd.np.random.randn(len(rng)), index=rng)
ts['2011-01-01':'2011-01-05']=pd.np.nan #a short length of NANs to timeseries
ts['2011-10-03':'2011-10-30']=pd.np.nan #add ~ month long length of NANs to timeseries

1 月份只有几个 NAN,但 10 月份几乎有整整一个月的 NAN,我想要我的每月重采样总和的输出:

ts.resample('M').sum()

给出 10 月份的 NAN(> 90% 的日常数据缺失)和 1 月份的值(< 90% 的数据缺失),而不是当前输出:

2011-01-31    11.949479
2011-02-28    -1.730698
2011-03-31    -0.141164
2011-04-30    -0.291702
2011-05-31    -1.996223
2011-06-30    -1.936878
2011-07-31     5.025407
2011-08-31    -1.344950
2011-09-30    -2.035502
2011-10-31    -2.571338
2011-11-30   -13.492956
2011-12-31     7.100770

我读过 this post , 使用滚动平均值和 min_periods;我宁愿继续使用 resample 来直接使用时间索引。这可能吗?我无法在重采样文档或堆栈溢出中找到很多内容来解决这个问题。

最佳答案

在使用 resample 时获取非空值的总和和计数,然后使用非空计数适本地更改总和:

# resample getting a sum and non-null count
ts = ts.resample('M').agg(['sum', 'count'])

# determine invalid months
invalid = ts['count'] <= 0.1 * ts.index.days_in_month

# restrict to the sum and null out invalid entries
ts = ts['sum']
ts[invalid] = np.nan

或者,您可以编写一个自定义求和函数在内部执行此过滤,但它在大型数据集上可能效率不高:

def sum_valid_obs(x):
    min_obs = 0.1 * x.index[0].days_in_month
    valid_obs = x.notnull().sum()
    if valid_obs < min_obs:
        return np.nan
    return x.sum()


ts = ts.resample('M').apply(sum_valid_obs)

任一方法的结果输出:

2011-01-31     3.574859
2011-02-28     2.907705
2011-03-31   -10.060877
2011-04-30     3.270250
2011-05-31    -3.492617
2011-06-30    -1.855461
2011-07-31    -7.363193
2011-08-31     0.128842
2011-09-30    -9.509890
2011-10-31          NaN
2011-11-30     0.543561
2011-12-31     3.354250
Freq: M, Name: sum, dtype: float64

关于python - 以最少的观察次数对 Pandas 进行重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019245/

相关文章:

Python 等效于 R c() 函数,用于数据框列索引?

python - 如何更改seaborn散点图中的专色边缘颜色

python - Numpy 将相同形状的向量附加到不同的轴

python - 从重复轴重新索引

python - 在 pandas 数据框中寻找值(value)

pandas 结合滚动和重新采样

audio - FFmpeg - 从 AV_SAMPLE_FMT_FLTP 重采样到 AV_SAMPLE_FMT_S16 音质非常差(缓慢、走调、噪音)

python - 使用 Pandas 在将每日数据转换为每周数据时格式化索引

python - PyQt,如何更改 BoxLayout 的权重(大小)

python - 如何在FastAPI中为上传文件创建OpenAPI架构?