python - Pandas 索引插值填充最后一个数据点之后的缺失值

标签 python pandas dataframe interpolation

在列末尾有一个缺少值的数据框,例如:

df = pd.DataFrame({'a':[np.nan,1,2,np.nan,np.nan,5,np.nan,np.nan]}, index=[0,1,2,3,4,5,6,7])

     a
0  NaN
1  1.0
2  2.0
3  NaN
4  NaN
5  5.0
6  NaN
7  NaN

使用“索引”插值方法:

df.interpolate(method='index')

返回数据帧,并向前填充最后一个缺失值:

     a
0  NaN
1  1.0
2  2.0
3  3.0
4  4.0
5  5.0
6  5.0
7  5.0

有没有办法关闭该行为并保留最后缺失的值:

     a
0  NaN
1  1.0
2  2.0
3  3.0
4  4.0
5  5.0
6  NaN
7  NaN

最佳答案

我认为0.23.0+中需要新参数limit_direction,请检查this :

df = df.interpolate(method='index', limit=1, limit_direction='backward')
print (df)
     a
1  1.0
2  2.0
3  3.0
4  4.0
5  5.0
6  NaN
7  NaN

编辑:如果想仅在添加参数limit_area内替换NaN:

df = df.interpolate(method='index',limit_area='inside')
print (df)
     a
0  NaN
1  1.0
2  2.0
3  3.0
4  4.0
5  5.0
6  NaN
7  NaN

关于python - Pandas 索引插值填充最后一个数据点之后的缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376792/

相关文章:

python - 从现有的日期列创建新列 "Week"

python - 如何从 Python 数据框列中的字符串中删除非字母数字字符?

python - 将带有日期时间索引的行插入数据框

python - MSYS2 和嵌入 Python。没有名为 'encodings' 的模块

python - 设置最大线程以保持主线程的更好解决方案?

python - 读取大型 csv 文件中特定列的最有效方法

python - 在 python 中使用数据框实现函数

python - 按字母顺序对数据类型进行排序

python - pandas-dev 安装(如何安装 Pandas 1.3.0)

python - 如何选择两个特殊字符之间的数据? Python