Jacob Myer
Jacob Myer

Reputation: 509

how to fill NaN values of Pandas column with values from another column

I have a column with missing values after a certain number of rows, and another column with missing values up to that point. How can I join the two columns so that I have one column with all the values?

Columns as is:

         COL 1      COL 2 
0            A        NaN
1            B        NaN  
2            C        NaN 
3          NaN          D   
4          NaN          E
5          NaN          F

Expected output:

         COL 1      
0            A             
1            B             
2            C            
3            D           
4            E          
5            F           

Upvotes: 2

Views: 580

Answers (2)

davidbilla
davidbilla

Reputation: 2222

You have to use fillna() with 'COL2' values on 'COL1' and then drop 'COL2'

df['COL1'] = df['COL1'].fillna(df['COL2'])
df = df.drop(columns='COL2')

Upvotes: 1

jezrael
jezrael

Reputation: 863541

Use Series.fillna or Series.combine_first:

df['COL 1'] = df['COL 1'].fillna(df['COL 2'])

df['COL 1'] = df['COL 1'].combine_first(df['COL 2'])

If want also remove second column add DataFrame.pop:

df['COL 1'] = df['COL 1'].fillna(df.pop('COL 2'))
#df['COL 1'] = df['COL 1'].combine_first(df.pop('COL 2'))

Upvotes: 5

Related Questions