Python 前向填充熊猫数据框中的特定列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27012151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
forward fill specific columns in pandas dataframe
提问by azuric
If I have a dataframe df with multiple columns ['x', 'y', 'z'] how do I forward fill only one column 'x' or a group of columns ['x','y']?
如果我有一个包含多列 ['x', 'y', 'z'] 的数据框 df,我如何仅向前填充一列 'x' 或一组列 ['x','y']?
I only know how to do it by axis.
我只知道如何通过轴来做到这一点。
采纳答案by Hennep
tl;dr:
tl;博士:
cols = ['X', 'Y']
df.loc[:,cols] = df.loc[:,cols].ffill()
And I have also added a self containing example:
而且我还添加了一个自包含示例:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> ## create dataframe
... ts1 = [0, 1, np.nan, np.nan, np.nan, np.nan]
>>> ts2 = [0, 2, np.nan, 3, np.nan, np.nan]
>>> d = {'X': ts1, 'Y': ts2, 'Z': ts2}
>>> df = pd.DataFrame(data=d)
>>> print(df.head())
X Y Z
0 0 0 0
1 1 2 2
2 NaN NaN NaN
3 NaN 3 3
4 NaN NaN NaN
>>>
>>> ## apply forward fill
... cols = ['X', 'Y']
>>> df.loc[:,cols] = df.loc[:,cols].ffill()
>>> print(df.head())
X Y Z
0 0 0 0
1 1 2 2
2 1 2 NaN
3 1 3 3
4 1 3 NaN
回答by Woody Pride
for col in ['X', 'Y']:
df[col] = df[col].ffill()
回答by Abhishek Chaurasia
I used below code, Here for X and Y method can be different also instead of ffill().
我使用了下面的代码,这里的 X 和 Y 方法也可以不同,而不是ffill()。
df1 = df.fillna({
'X' : df['X'].ffill(),
'Y' : df['Y'].ffill(),
})
回答by Souvik Daw
Two columns can be ffill()simultaneously as given below:
两列可以ffill()同时出现,如下所示:
df1 = df[['X','Y']].ffill()

