Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas how to check if column not empty then apply .str.replace in one line code

code:

df['Rep'] = df['Rep'].str.replace('\\n', ' ')

issue:
if the df[‘Rep’] is empty or null ,there will be an error:

Failed: Can only use .str accessor with string values!

is there anyway can handle the situation when the column value is empty or null? If it is empty or null ,just ignore that row

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By default the empty series dtype will be float64.

You can do a workaround using the astype:

df['Rep'] = df['Rep'].astype('str').str.replace('\\n', ' ')

Test code:

df = pd.DataFrame({'Rep': []})

# works
df['Rep'] = df['Rep'].astype('str').str.replace('\\n', ' ')

# doesn't work
df['Rep'] = df['Rep'].str.replace('\\n', ' ')

I don’t know which version of pandas you are using by they will changed to object the default dtype.

Edit: Still won’t work with object, just tested using the latest version of pandas (2.0.0).

Source

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading