我有一个数据表:
Index Value
0 NaN
1 1.15
2 2.25
3 2.33
条件:首先检查上一行值不是NaN的地方,然后用上一行值替换当前行值。
所需的输出:
Index Value
0 NaN
1 1.15
2 1.15
3 1.15
答案 0 :(得分:1)
比较缺失值的值,然后获取第一个连续值并用DataFrame.where
替换另一个值,向前填充缺失值,最后替换原始缺失值:
df = pd.DataFrame({'Value':[np.nan,1.15,2.15,3.15,np.nan,2.1,2.2,2.3]})
m = df.notna()
df1 = df.where(m.ne(m.shift())).ffill().where(m)
print (df1)
Value
0 NaN
1 1.15
2 1.15
3 1.15
4 NaN
5 2.10
6 2.10
7 2.10
详细信息:
print (m.ne(m.shift()))
Value
0 True
1 True
2 False
3 False
4 True
5 True
6 False
7 False
print (df.where(m.ne(m.shift())))
Value
0 NaN
1 1.15
2 NaN
3 NaN
4 NaN
5 2.10
6 NaN
7 NaN
print (df.where(m.ne(m.shift())).ffill())
Value
0 NaN
1 1.15
2 1.15
3 1.15
4 1.15
5 2.10
6 2.10
7 2.10