Reputation: 53
I have this for with the name of the text columns of my Dataframe, I want to replace the '' and nan by None for the database to be NULL, but when I try to replace nan to None it gives an error, so I tried to change from nan to '' and then None, but it is sending to the bank as a string "None"
for item in ['column1', 'column2', 'column3']:
DataFrame[item] = DataFrame[item].astype(str).str.strip().replace('nan', np.nan).replace(np.nan, '').replace('', None)
del item
Does anyone know how to fix this or have a better idea of how to replace empty texts or 'nan' with None?
Upvotes: 0
Views: 206
Reputation: 72
Change it to the line below instead
DataFrame[item] = DataFrame[item].astype(str).str.strip().replace('nan', np.nan).replace('', None).replace(np.nan, None)
I wrote a small test for it below :
import pandas as pd
import numpy as np
# Set up the test data
data = {'item': ['abc', '', 'def', 'nan', np.nan, 'ghi']}
DataFrame = pd.DataFrame(data)
# Apply the modified code to the 'item' column of the DataFrame
DataFrame['item'] = DataFrame['item'].astype(str).str.strip().replace('nan', np.nan).replace('', None).replace(np.nan, None)
# Verify that the values in the 'item' column are as expected
expected = ['abc', None, 'def', None, None, 'ghi']
assert (DataFrame['item'].values == expected).all()
I hope it helps
Upvotes: 1