使用pandas替换csv文件中的NaN值,并将其存储到MySQL中,可以按照以下步骤进行操作:
import pandas as pd
import numpy as np
import pymysql
from sqlalchemy import create_engine
df = pd.read_csv('your_file.csv')
df = df.fillna(value=np.nan) # 将所有NaN值替换为np.nan
host = 'your_host'
port = your_port
user = 'your_username'
password = 'your_password'
database = 'your_database'
conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
table_name = 'your_table_name'
# 创建引擎
engine = create_engine(f'mysql+pymysql://{user}:{password}@{host}:{port}/{database}')
# 将DataFrame写入MySQL数据库
df.to_sql(name=table_name, con=engine, if_exists='replace', index=False)
conn.close()
完整的代码示例如下:
import pandas as pd
import numpy as np
import pymysql
from sqlalchemy import create_engine
# 读取CSV文件并替换NaN值
df = pd.read_csv('your_file.csv')
df = df.fillna(value=np.nan) # 将所有NaN值替换为np.nan
# 连接到MySQL数据库
host = 'your_host'
port = your_port
user = 'your_username'
password = 'your_password'
database = 'your_database'
conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database)
# 创建数据库表(如果需要)
table_name = 'your_table_name'
# 创建引擎
engine = create_engine(f'mysql+pymysql://{user}:{password}@{host}:{port}/{database}')
# 将DataFrame写入MySQL数据库
df.to_sql(name=table_name, con=engine, if_exists='replace', index=False)
# 关闭数据库连接
conn.close()
这样,你就可以使用pandas替换CSV文件中的NaN值,并将其存储到MySQL数据库中了。
领取专属 10元无门槛券
手把手带您无忧上云