Convert dataframe values into str where is not null (None)

I need to ingest data into a SQL Server database using Python, so in order to do that I’m casting all my dataframe into str before:

df = df.astype(str)

But if my dataframe has null values as None, the None word is also casting as string and ingested as string into my database as well as example below.

Row Type
1 None
2 projects
3 projects
4 projects
5 None

I couldn’t find a way to apply a cast using astype(str) in my dataframe where the values is not null.

The output I need:

Row Type
2 projects
3 projects
4 projects

What is the best way to do that?


I’m already using for the whole dataframe because I’ve got a lot of columns: df = df.str.replace('None', ''), but I’m afraid any “None” word can appear somewhere and be replaced wrong.


Use str.replace:

# After df = df.astype(str)
df['Type'] = df['Type'].str.replace('None', '')


>>> df
   Row       Type
0     1
1     2  projects
2     3  projects
3     4  projects
4     5


According to your comment, the method below replace cells that contain only None over your whole dataframe.

df = df.replace(r'^None$', '', regex=True)

Note: ^ matches the start of line and $ matches the end of line.