pandasdataframenanffill

pandas dataframe how to ffill nan columns when number of nan differ between rows


I have a dataframe, when every row might have some nan in the last columns:

df = 
A B C  D   E   F
1 2 3 nan nan nan
1 2 3  4  nan nan
1 2 3  4   5   6 

I want to run ffill per row, to get:

df = 
A B C  D  E F
1 2 3  3  3 3
1 2 3  4  4 4
1 2 3  4  5 6 

How can I do it?

Thanks


Solution

  • Use ffill with axis=1 as parameter:

    >>> df.ffill(axis=1).astype(int)
       A  B  C  D  E  F
    0  1  2  3  3  3  3
    1  1  2  3  4  4  4
    2  1  2  3  4  5  6