简体   繁体   English

用 Python 中最接近的非 NaN 列值填充 NaN

[英]Fill NaN with the closest not NaN columns values in Python

I want to fill e column's NaN with its most closest (by position from left side) not NaN columns' values.我想用最接近的(从左侧的位置) not NaN列的值填充e列的NaN

   a    b    c    d    e
0  1  2.0  3.0  6.0  3.0
1  3  5.0  7.0  NaN  NaN
2  2  4.0  NaN  NaN  NaN
3  5  6.0  NaN  NaN  NaN
4  3  NaN  NaN  NaN  NaN

For example, for the second row of e , its most closest Not NaN column is e by position, then we take 7.0 , is it possible to do this in Pandas?例如,对于e的第二行,它最接近的Not NaN列是e by position,那么我们取7.0 ,在 Pandas 中可以这样做吗? Thanks.谢谢。

The expected output is like this:预期的输出是这样的:

   a    b    c    d    e
0  1  2.0  3.0  6.0  3.0
1  3  5.0  7.0  NaN  7.0
2  2  4.0  NaN  NaN  4.0
3  5  6.0  NaN  NaN  6.0
4  3  NaN  NaN  NaN  3.0

如果答案应该是简化获取从左侧到最后一列的所有第一个非缺失值,使用向前填充它们并按位置选择最后一列:

df.e = df.ffill(axis=1).iloc[:, -1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM