python - 如何返回带有滚动窗口但没有应用附加功能的熊猫数据框?
问题描述
我有一个数据框,我想忽略(替换为 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
返回错误。
解决方案
您可以遍历窗口并仅保留具有一定数量的 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()
推荐阅读
- pgadmin - 无法在 pgadmin4 中关闭输出窗格
- python - 我无法从 conda 环境导入 cv2
- python - 合并两个添加了相同键值的字典列表,如果找不到键仍然添加值
- c++ - 为什么 std::endl 让这个循环永远运行?
- node.js - 错误:传入的 JSON 对象在 JWT.fromJSON 中不包含 client_email 字段
- python - 对 Y 轴值进行排序
- javascript - 如何在上传时获取云小部件图像信息?
- java - 如何等到所有一系列嵌套的 CompletableFuture 都完成?
- ios - RequestLocation 耗时过长
- java - 在java中返回整数数组时获取java.lang.NullPointerException