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

末鹿安然 提交于 2019-12-18 09:32:58

问题


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.


回答1:


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



回答2:


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

df.ffill(axis=0)


来源:https://stackoverflow.com/questions/47087907/how-to-fill-nan-value-with-the-previous-available-in-the-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!