python - pandas ewm 和滚动方法不填写 NA

标签 python pandas

是否有 ewm 和滚动方法的参数不填写 NA?

>>> A = pd.Series([1,2,3,4,np.nan,5,6])
>>> A
0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
5    5.0
6    6.0
dtype: float64
>>> eA = A.ewm(alpha = 0.5, ignore_na=True).mean()
>>> eA
0    1.000000
1    1.666667
2    2.428571
3    3.266667
4    3.266667 # I want this to be NA, don't fill in
5    4.161290
6    5.095238
dtype: float64

当然这很容易解决

eA[A.isnull()] = np.nan

但这会花费一些不必要的运行时间,并且当您有多个滚动函数时,需要为每个滚动函数考虑一个变量名称,这很麻烦。

最佳答案

不幸的是,ewm 目前不支持此功能。 ,您必须使用建议的方法用 NaN 覆盖或过滤 NaN 行,以便 ewm 生成 Series 保留原始索引,然后您可以使用 combine_firstreindex重新插入 NaN 行:

In [32]:
A = pd.Series([1,2,3,4,np.nan,5,6])
eA = A[A.notnull()].ewm(alpha = 0.5, ignore_na=True).mean()
eA.combine_first(A)

Out[32]:
0    1.000000
1    1.666667
2    2.428571
3    3.266667
4         NaN
5    4.161290
6    5.095238
dtype: float64

In [33]:
eA.reindex(A.index)

Out[33]:
0    1.000000
1    1.666667
2    2.428571
3    3.266667
4         NaN
5    4.161290
6    5.095238
dtype: float64

关于python - pandas ewm 和滚动方法不填写 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975812/

相关文章:

python - Pandas Dataframe Groupby 连接字符串,同时保留字符串的顺序

pandas - 通过对 Pandas 中的某些列求和来组合多个数据框

javascript - pandas to_json 返回一个字符串而不是一个 json 对象

python - 使用 Pandas 创建大型数据框

python - 使用子字符串将字典转换为列表

python - python2中的类方法钩子(Hook)装饰器

python - 为什么 aiohttp 不允许在 url 路径中使用冒号?

python - 如何使用子进程在当前激活的 virtualenv 中运行 python 代码?

python - 图例中的错误栏- Pandas 栏图

python - 如何减少重复的 try/catch block ?