简单使用 :pandas 数据清洗

Python爬虫scrapy

共 1760字,需浏览 4分钟

 · 2021-04-14

读取数据

  • 使用 pd 的 read_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)

空值空格处理

  • 处理空值以及空格使用 pd 的 strip 方法以及 dropna 方法

df['product_name'].str.strip() 
# 删除列 `product_name` 为 `NaN` 的行
df.dropna(subset=['product_name'], inplace=True)

异常值处理

  • 处理异常值使用 pd 的 replace 方法

df.replace(' ', np.nan, inplace=True)

数据重新写入到 MySQL

  • 数据重新写入 MySQL 使用 pd 的 to_sql 方法

df.to_sql(name=table_name, con=self.conn, if_exists='append', index=True)

pandas 设置

#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#设置 value 的显示长度为 100,默认为 50
pd.set_option('max_colwidth',100)

问题

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)



浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报