我有一个包含以下数据的数据框:
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%
有没有一种方法可以不使用循环来实现?
最佳答案
使用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%
关于python - 将行值重复X次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58677776/