python - 为什么 pandas.interpolate() 插入由 NaN 包围的单个值?

标签 python pandas interpolation

我在 pandas interpolate() 方面遇到问题。我只想在不超过 2 个连续的“np.nans”时进行插值。 但是当 np.nan 超过 2 个时,插值函数会尝试对单个值进行插值!?

s = pd.Series(data = [np.nan,10,np.nan,np.nan,np.nan,5,np.nan,6,np.nan,np.nan,30])
a = s.interpolate(limit=2,limit_area='inside')
print(a)

我得到的输出是:

0       NaN
1     10.00
2      8.75
3      7.50
4       NaN
5      5.00
6      5.50
7      6.00
8     14.00
9     22.00
10    30.00
dtype: float64

我不想要第 2 行和第 3 行的结果。 我想要的是:

0       NaN
1     10.00
2       NaN
3       NaN
4       NaN
5      5.00
6      5.50
7      6.00
8     14.00
9     22.00
10    30.00
dtype: float64

有人可以帮忙吗?

最佳答案

<强> Groupby.transformSeries.where

s_notna = s.notna()
m = (s.groupby(s_notna.cumsum()).transform('size').le(3) | s_notna)    
s = s.interpolate(limit_are='inside').where(m)
print(s)

输出

0      NaN
1     10.0
2      NaN
3      NaN
4      NaN
5      5.0
6      5.5
7      6.0
8     14.0
9     22.0
10    30.0
dtype: float64

关于python - 为什么 pandas.interpolate() 插入由 NaN 包围的单个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812935/

相关文章:

python - 将数据从 BigQuery 加载到 Redis 中

python - 使用 gcloud python 将空数据上传到 Bigquery

python - 如何使用 statsmodels Holt-Winters 预测时间序列集

Pandas:插入缺失的行数据并在组内使用条件进行迭代

matlab - 绘制带有插值颜色的二维矩形

python - 为什么主要的可运行 Python 脚本没有编译为模块之类的 pyc 文件?

python - nltk中的pos_tag与UnigramTagger和BigramTagger有什么区别?

python - Pandas匹配数据帧结构

html - Angular - 无法连接 HTML 页面中的值

opengl - 如何通过线性插值执行快速 Catmull-Rom 纹理倾斜?