小编典典

向前填充熊猫数据框中的特定列

python

如果我有一个包含多列的数据框['x', 'y', 'z'],如何只填充一列'x'?还是一组列['x','y']

我只知道如何按轴进行操作。


阅读 170

收藏
2020-12-20

共1个答案

小编典典

tl; dr:

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
2020-12-20