Home > Enterprise >  Copy the values from another column if the column A has null values
Copy the values from another column if the column A has null values

Time:11-01

How to copy the values from column A to column B, if the column B has null values.

DATA:

   A        B      
12525    1FWE23   
14654        
24798         
38945         
46456    46485     
AD545    45346     
A5D66          

EXPECTED :

   A        B      
12525    1FWE23   
14654    14654    
24798    24798    
38945    38945     
46456    46485     
AD545    45346     
A5D66    A5D66      

CodePudding user response:

If your blank values are nan, you can just use fillna():

df['B'] = df['B'].fillna(df['A'])

   A        B      
12525    1FWE23   
14654    14654    
24798    24798    
38945    38945     
46456    46485     
AD545    45346     
A5D66    A5D66 

If they are empty strings, you can replace() them with nan and do the same:

import numpy as np
df['B'] = df['B'].replace("", np.nan).fillna(df['A'])

CodePudding user response:

If empty values are None:

df.B.fillna(df.A, inplace=True)

If empty values are empty string (""):

df.loc[df['B'] == '', 'B'] = df.loc[df['B'] == '', 'A']

CodePudding user response:

df['B'] = df['B'].fillna(df['A'])

The above code fixed the issue for me by replacing the blank values in the column B with the column A values

  • Related