简体   繁体   中英

Fill NaN values in dataframe with pandas

I have a dataframe that I created from a text file. Columns BF should apply to all null fields below them, then once all nulls are filled the next set of periods should be filled by the next values populated in BF. How would I go about accomplishing this?

数据框截图

You'll want to use the fillna() method of DataFrames, with a forward-fill:

df.fillna(method='ffill')

Here's a quick example:

df = pd.DataFrame({'A': [4, None, None, 5, None, None],
                   'B': [2, None, None, 3, None, None],
                   'C': range(6)})

>>> df
    A   B  C
0   4   2  0
1 NaN NaN  1
2 NaN NaN  2
3   5   3  3
4 NaN NaN  4
5 NaN NaN  5

>>> df.fillna(method='ffill')
   A  B  C
0  4  2  0
1  4  2  1
2  4  2  2
3  5  3  3
4  5  3  4
5  5  3  5

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM