Home > front end >  Python: How to ffill and bfill a column with nan?
Python: How to ffill and bfill a column with nan?

Time:12-04

How might I ffill and bfill a column that contains nans?

Consider this example:

# data
df = pd.DataFrame([
            [np.nan, '2019-01-01', 'P', 'O', 'A'],
            [np.nan, '2019-01-02', 'O', 'O', 'A'],
            ['A', '2019-01-03', 'O', 'O', 'A'],
            ['A', '2019-01-04', 'O', 'P', 'A'],
            [np.nan, '2019-01-05', 'O', 'P', 'A'],
            [np.nan, '2019-01-01', 'P', 'O', 'B'],
            ['B', '2019-01-02', 'O', 'O', 'B'],
            ['B', '2019-01-03', 'O', 'O', 'B'],
            ['B', '2019-01-04', 'O', 'P', 'B'],
            [np.nan, '2019-01-05', 'O', 'P', 'B'],
            ], columns=['ID', 'Time', 'FromState', 'ToState', 'Expected'])

# updated try
df['ID'] = df['ID'].transform(lambda x: x.ffill().bfill() )

CodePudding user response:

The following works for me:

df['ID'] = df['ID'].ffill(limit=1).bfill(limit=2)
  • Related