biohazard90
biohazard90

Reputation: 115

How to fill NaN cells in a pandas dataframe, based on the previous column?

I have the following DF

col1| col2
 123| NaN
 234| 234
 456| NaN
 567| 567

and what I want to do, is to copy the left cell to the right cell if the right cell is empty, so the output is

col1| col2
 123| 123
 234| 234
 456| 456
 567| 567

I tried to work something with fillna, but failed miserably

Upvotes: 1

Views: 509

Answers (3)

sophocles
sophocles

Reputation: 13821

You can use np.where from the numpy package

Assuming your dataframe is called df:

import numpy as np
df['col2'] = np.where(df['col2'].isnull(),df['col1'],df['col2'])

which will give you:

col1| col2
 123| 123
 234| 234
 456| 456
 567| 567

Upvotes: 1

Ehtisham Ahmed
Ehtisham Ahmed

Reputation: 387

df.fillna(method='ffill',axis=1)

Upvotes: 2

jezrael
jezrael

Reputation: 862481

Use ffill by columns, so axis=1:

df = df.ffill(axis=1)
print (df)
    col1   col2
0  123.0  123.0
1  234.0  234.0
2  456.0  456.0
3  567.0  567.0

Upvotes: 2

Related Questions