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 word is also casting as string and ingested as string into my database as well as example below.
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:
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.
# 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)
^ matches the start of line and
$ matches the end of line.