Mysteri0n
Mysteri0n

Reputation: 167

Fill NaN values in dataframe with pandas

I have a dataframe that I created from a text file. Columns B-F 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 B-F. How would I go about accomplishing this?

Dataframe Screenshot

Upvotes: 0

Views: 498

Answers (1)

jakevdp
jakevdp

Reputation: 86320

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

Upvotes: 5

Related Questions