首页 > 解决方案 > 如何返回带有滚动窗口但没有应用附加功能的熊猫数据框?

问题描述

我有一个数据框,我想忽略(替换为 NaN)在滚动窗口中没有足够非 NaN 值的值。可以通过以下方式重新创建示例数据框:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
for col in df.columns:
    df.loc[df.sample(frac=0.25).index, col] = np.nan  

       A     B     C     D
0   38.0  39.0   NaN  82.0
1   44.0  47.0   NaN   NaN
2    NaN  24.0  67.0   NaN
3   96.0   NaN   NaN  68.0
4   53.0   NaN  27.0  93.0

min_periods我想创建一个宽度为 4 的滚动窗口,对于每个窗口,如果那里至少有非 NaN 值,我只想保留该值。

我认为这将是微不足道的,只需使用:

df.rolling(4, min_periods=2).apply(lambda x: x)

但是,它似乎apply不允许这样的 lambda 函数,并pandas.core.base.DataError: No numeric types to aggregate返回错误。

标签: pythonpandas

解决方案


您可以遍历窗口并仅保留具有一定数量的 nan 值(或相反)的窗口。

windowed_ds = df.rolling(4,min_periods=2)
windows_2_keep = []
for w in windowed_ds:
    # total nan values in window
    total_is_na_in_window = w.isna().sum().sum()
    # keep only windows with more than 2 nan values
    if total_is_na_in_window >2:
        windows_2_keep.append(w)
    # we can also do operations like mean or sum on each window
    # window_mean = w.mean().mean()

推荐阅读