Skip to content Skip to sidebar Skip to footer

Change Axis For Pandas Replace Ffill

Suppose I have a dataframe that looks like: df = 0 1 2 0 1.0 2.0 3.0 1 4.0 5.0 NaN 2 6.0 NaN NaN Then it is possible to use df.fillna(method='ffill', a

Solution 1:

Use mask and ffill

df.mask(df.eq(-1)).ffill(axis=1)

     01201.02.03.014.05.05.026.06.06.0

Solution 2:

You can convert your -1 values to NaN before using pd.DataFrame.ffill:

print(df)

     0    1    2
0  1.0  2.0  3.0
1  4.0  5.0 -1.0
2  6.0 -1.0 -1.0

res = df.replace(-1, np.nan)\
        .ffill(axis=1)

print(res)

     0    1    2
0  1.0  2.0  3.0
1  4.0  5.0  5.0
2  6.0  6.0  6.0

Solution 3:

IIUC, use mask and ffill with axis=1:

Where df1 = df.fillna(-1.0)

df1.mask(df1 == -1).ffill(1)

Output:

     0    1    2
0  1.0  2.0  3.0
1  4.0  5.0  5.0
2  6.0  6.0  6.0

Post a Comment for "Change Axis For Pandas Replace Ffill"