Skip to content
Advertisement

Python skip empty cells

I want to be able to search through my dataframe and skip cells that are blank. However, when i read in the DF it reads the blanks as “nan”

DF1

Name Address1 Street      Town   Postcode
Will nan      nan        London   nan
Phil 19      Long Road     nan    nan

I want to be able to filter through Address1, Street and Town. If there is text inside of those columns I want to add a “|” at the start but if there is no text inside of the column it skips that cell and doesn’t add the “|”

Desired Result

Name Address1 Street      Town   Postcode
Will                     |London 
Phil 19      |Long Road

Advertisement

Answer

Something like this?

import numpy as np
for i in ['Address1','Street','Town']:
    df[i] = np.where(df[i].notnull(),'|' + df[i].astype(str),'')

Which prints:

print(df)

   Name Address1       Street     Town  Postcode
0  Will                        |London       nan
1  Phil    |19.0  |Long Road                nan
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement