forward fill specific columns in pandas dataframe

前端 未结 4 670
一生所求
一生所求 2020-11-28 09:50

If I have a dataframe with multiple columns [\'x\', \'y\', \'z\'], how do I forward fill only one column \'x\'? Or a group of columns [\'x\',

相关标签:
4条回答
  • 2020-11-28 10:16
    for col in ['X', 'Y']:
        df[col] = df[col].ffill()
    
    0 讨论(0)
  • 2020-11-28 10:20

    tl;dr:

    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
    
    0 讨论(0)
  • 2020-11-28 10:26

    I used below code, Here for X and Y method can be different also instead of ffill().

     df1 = df.fillna({
            'X' : df['X'].ffill(),
            'Y' : df['Y'].ffill(),
        })
    
    0 讨论(0)
  • 2020-11-28 10:33

    Two columns can be ffill() simultaneously as given below:

    df1 = df[['X','Y']].ffill()
    
    0 讨论(0)
提交回复
热议问题