Skip to main content
 首页 » 编程设计

python之ffill 不保留所有列

2024年10月24日9落叶无声

我有一个这样的 df:

Key    Class 
1      Green 
1      NaN 
1      NaN 
2      Red 
2      NaN 
2      NaN 

我想转发填充 Class。我正在使用这段代码:

df=df.Class.fillna(method='ffill') 

这会返回:

Green 
Green 
Green 
Red 
Red 
Red 

如何在执行此操作时保留 Key 列?

请您参考如下方法:

df['class'] = df.Class.fillna(method='ffill') 

在您的代码中,您将整个数据框指定为结果,因此您只需要指定 class 列

或者另一种方法是执行以下操作

In [126]: 
df.ffill() 
Out[126]: 
    Key Class 
0   1   Green 
1   1   Green 
2   1   Green 
3   2   Red 
4   2   Red 
5   2   Red 

如果你不想从你的df创建一个新的副本,你也可以将inplace参数设置为true

df.ffill(inplace=True)