1

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

biohazard90
  • 95
  • 1
  • 7
  • @jezrael Check [`this`](https://stackoverflow.com/questions/48521360/pandas-fill-nan-based-on-the-previous-value-of-another-cell) out. If this looks close to you? – Mayank Porwal Nov 11 '20 at 14:17

3 Answers3

2

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2
df.fillna(method='ffill',axis=1)
Ehtisham Ahmed
  • 387
  • 3
  • 15
1

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
sophocles
  • 13,593
  • 3
  • 14
  • 33