简体   繁体   中英

Python code sending None record as "None" to the database

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

Image

Does anyone know how to fix this or have a better idea of how to replace empty texts or 'nan' with None?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM