Convert column to string where have pandas null values

Asked

Viewed 1,593 times

0

How do I convert a column to string every time I try to do

`df['COL1'] = ['COL1'].astype(str)`

where there are nulls, pandas convert to string "NAN", have some way around this problem?

1 answer

2


you can use a lambda function:

f = lambda x: '' if type(x) == np.nan else str(x)

Dae just apply the column

df['COL1'] = ['COL1'].apply(f)

if it doesn’t work. You can turn it into a string first and use the function.

df['COL1'] = ['COL1'].astype(str)
f = lambda x: '' if x = 'NAN' else str(x)

if you want to replace these values with other things just use . fillnan().

df['COL1'] = ['COL1'].fillna(' ') #Ele ira colocar ' ' no lugar dos NAN.

If you want the values to remain Nan uses the function:

f = lambda x: np.nan if x == np.nan else str(x)
df['COL1'] = ['COL1'].apply(f)

depending on the version of the pandas this can be problematic if use problem:

f = lambda x: np.nan if str(x) == 'NAN' else x
df['COL1'] = ['COL1'].apply(f)

I hope I’ve helped

I hope I’ve helped

  • That way you put empty values, I needed them to remain null

  • I edited the answer look there now.

  • In this case it worked f = lambda x: np.nan if x == np.nan else str(x)
df['COL1'] = ['COL1'].apply(f)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.