我提取了一个具有特定值的单列数据框。现在,数据框如下所示:

           Commodity
0              Cocoa
4             Coffee
6              Maize
7               Rice
10             Sugar
12             Wheat


现在,我想用该列上方的值分别填充每个没有值的索引,因此它看起来应该像这样:

            Commodity
0               Cocoa
1               Cocoa
2               Cocoa
3               Cocoa
4              Coffee
5              Coffee
6               Maize
7                Rice
8                Rice
9                Rice
10              Sugar
11              Sugar
12              Wheat


我似乎没有从pandas文档“使用文本数据”中得到任何帮助。谢谢你的帮助!

最佳答案

我用pd.RangeIndex创建一个新索引。它的作用类似于range,因此我需要给它传递一个比当前索引中的最大数字大一的数字。

df.reindex(pd.RangeIndex(df.index.max() + 1)).ffill()

   Commodity
0      Cocoa
1      Cocoa
2      Cocoa
3      Cocoa
4     Coffee
5     Coffee
6      Maize
7       Rice
8       Rice
9       Rice
10     Sugar
11     Sugar
12     Wheat

09-26 17:30
查看更多