我有一个包含以下数据的数据框:
Stock: Bond: Gold:
2/01/19 NaN NaN NaN
1/31/19 NaN NaN NaN
1/30/19 33% 33% 33%
1/29/19 NaN NaN NaN
1/28/19 NaN NaN NaN
1/27/19 50% 20% 30%
1/26/19 NaN NaN NaN
1/25/19 NaN NaN NaN
1/24/19 NaN NaN NaN
1/23/19 NaN NaN NaN
1/22/29 40% 50% 10%
我希望将所有NaN替换为其下面的%值,以便最终输出如下所示:
Stock: Bond: Gold:
2/01/19 33% 33% 33%
1/31/19 33% 33% 33%
1/30/19 33% 33% 33%
1/29/19 50% 20% 30%
1/28/19 50% 20% 30%
1/27/19 50% 20% 30%
1/26/19 40% 50% 10%
1/25/19 40% 50% 10%
1/24/19 40% 50% 10%
1/23/19 40% 50% 10%
1/22/29 40% 50% 10%
有没有一种方法可以不使用循环?
答案 0 :(得分:2)
使用bfill
来回填缺失值,DataFrame.fillna
的缩写是method='bfill'
:
df = df.bfill()
#alternative
#df = df.fillna(method='bfill')
print (df)
Stock: Bond: Gold:
2/01/19 33% 33% 33%
1/31/19 33% 33% 33%
1/30/19 33% 33% 33%
1/29/19 50% 20% 30%
1/28/19 50% 20% 30%
1/27/19 50% 20% 30%
1/26/19 40% 50% 10%
1/25/19 40% 50% 10%
1/24/19 40% 50% 10%
1/23/19 40% 50% 10%
1/22/29 40% 50% 10%