I have a dataframe let's say
df = pd.DataFrame({'first':['fillwithit',None,None,'restbyit', None, None], 'test':[1,2,3,4,5,6]})
>>>In [10]: df
Out[10]:
first test
0 fillwithit 1
1 None 2
2 None 3
3 restbyit 4
4 None 5
5 None 6
What I want is to fill all the None, such that None will look above it, find the first Non-None value, and fill it by it.
For example, None at index 1 and 2 will be filled via fillwithit and 4 & 5 via restbyit.
Output should be like
In [12]: df
Out[12]:
first test
0 fillwithit 1
1 fillwithit 2
2 fillwithit 3
3 restbyit 4
4 restbyit 5
5 restbyit 6
I am thinking of a manual for looped version, but it seems inefficient. Do you have any better solution?
just put it here for reference:
import pandas as pd
df = pd.DataFrame({'first':['fillwithit',None,None,'restbyit', None, None], 'test':[1,2,3,4,5,6]})
df = df.ffill()
output:
first test
0 fillwithit 1
1 fillwithit 2
2 fillwithit 3
3 restbyit 4
4 restbyit 5
5 restbyit 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.