简体   繁体   English

将行值重复 X 次

[英]Repeat row values by X number of times

I have a dataframe with the following data:我有一个 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%

I want all the NaN to be replaced with the % value that's beneath it, so that the final output would like the below:我希望将所有 NaN 替换为其下方的 % 值,以便最终的 output 如下所示:

        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%

Is there a way to achieve this without using loops?有没有办法在不使用循环的情况下实现这一点?

Use back filling missing values by bfill , what is short version of DataFrame.fillna with method='bfill' :使用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%

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

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