Guido Muscioni
Guido Muscioni

Reputation: 1295

How to fill nan value with the previous available in the row?

I need to fill the nan value in a dataframe by using the previous available value in a row, as the data are timeseries. Here there is an example:

1   2   3   4
b   b   nan c
c   nan d   nan
d   nan nan c

What I need is:

1   2   3   4
b   b   b   c
c   c   d   d
d   d   d   c

I know the method fillna from panda, but the methods are only based on columns. I think about doing a transposition and after the use of the fillna method, but I would like to know if there are more efficient way to do that.

Upvotes: 1

Views: 1566

Answers (2)

If you want to fill nan cells by value from row in up:

df.ffill(axis=0)

Upvotes: -1

cs95
cs95

Reputation: 403278

Use ffill along the first axis.

df.ffill(axis=1)

   1  2  3  4
0  b  b  b  c
1  c  c  d  d
2  d  d  d  c

Upvotes: 2

Related Questions