在Pandas数据框中,向前填充特定列

61
如果我有一个包含多个列['x', 'y', 'z']的数据帧,如何仅填充一列 'x'?或一组列['x','y']
我只知道如何按轴填充。
6个回答

116

简而言之:

cols = ['X', 'Y']
df.loc[:,cols] = df.loc[:,cols].ffill()

我还添加了一个自包含的示例:

>>> 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

这会引发一个 SettingWithCopyWarning。对于这个警告有什么想法吗? - yeliabsalohcin
2
请参阅此处有关Python首选索引方式的说明:http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html 更改为.loc语句应该解决问题,我已相应地更新了答案。 - Hennep
如果我希望在填充数据时排除X和Y列,该怎么做? - ah bon
cols_ex = ['X', 'Y'] # define columns to exclude \\ cols = df.columns # get list with all columns \\ cols_to_ff = cols.drop(cols_ex) # drop columns to exclude \\ df.loc[:,cols_to_ff] = df.loc[:,cols_to_ff].ffill() # forward fill the selected columns \\ - Hennep
如果你想要向前填充的列就是索引呢? - undefined

19
for col in ['X', 'Y']:
    df[col] = df[col].ffill()

12

或者使用 inplace 参数:

df['X'].ffill(inplace=True)
df['Y'].ffill(inplace=True)

不,你不能这样做df[['X','Y']].ffill(inplace=True),因为这首先通过列选择创建了一个切片,因此 inplace 前向填充会创建一个 SettingWithCopyWarning。当然,如果你有一列列表,你可以在循环中执行这个操作:

for col in ['X', 'Y']:
    df[col].ffill(inplace=True)

使用 inplace 的目的在于避免复制该列。

5

以下是同时使用ffill()的两列:

df1 = df[['X','Y']].ffill()

1
我首先尝试了这个解决方案,因为它看起来更简洁,但是这个解决方案的一个问题是只有X列和Y列保存在df1数据框中。其余的列没有保存。Woody Pride和Abhishek Chaurasia的回答都保留了所有列。 - burkesquires

4
我使用了以下代码。在这里,X和Y方法也可能不同,而不是使用ffill()。
 df1 = df.fillna({
        'X' : df['X'].ffill(),
        'Y' : df['Y'].ffill(),
    })

1

我认为这是最简单的版本。

cols = ['X', 'Y']
df[cols] = df[cols].ffill()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接