将行值重复X次

时间:2019-11-03 05:57:43

标签: python pandas dataframe

我有一个包含以下数据的数据框:

        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%

有没有一种方法可以不使用循环?

1 个答案:

答案 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%