pandas 清洗 MySQL 数据

读取数据

  • 使用 pdread_sql 读取数据
import pymysql
import pandas as pd

self.conn = pymysql.connect(host=host, user=user,
password=pass, db=db, charset='utf8')

sql = 'select * from table_name'
df = pd.read_sql(sql, con=self.conn)

空值空格处理

  • 处理空值以及空格使用 pdstrip 方法以及 dropna 方法
df['product_name'].str.strip() 
# 删除列 `product_name` 为 `NaN` 的行 
df.dropna(subset=['product_name'], inplace=True)

异常值处理

  • 处理异常值使用 pdreplace 方法
df.replace(' ', np.nan, inplace=True)

数据重新写入到 MySQL

  • 数据重新写入 MySQL 使用 pdto_sql 方法
df.to_sql(name=table_name, con=self.conn, if_exists='append', index=True)

问题

1、pd 的 to_sql 不能使用 pymysql 的连接,否则就会直接报错

pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting

需要改为

from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://user:pass@host:port/db")

2、空值处理的问题

  • 保存在 mysql 中的数据中有空值,但是使用 pd.str.strip() 处理没有用

  • 使用 replace 替换空格、空值为 nan 也没有用

    解决办法:replace 使用正则替换

# 替换\r\n\t以及html中的\xa0
df.replace(r'\r|\t|\n|\xa0', '', regex=True, inplace=True)
# 替换空格,将空格替换为空字符串
df['product_name'].replace(r' ', '', regex=True, inplace=True)
# 将空字符串替换为 nan
df['product_name'].replace(r'', np.nan, regex=True, inplace=True)
# 将乱码替换替换为空字符串(正则为匹配不是中文、字母、数字组成的字符串)
df['product_name'].replace(r'[^\u4e00-\u9fa5_a-zA-Z0-9]', np.nan, regex=True, inplace=True)
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

裸睡的雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值