簡單使用 :pandas 數(shù)據(jù)清洗
讀取數(shù)據(jù)
使用
pd的read_sql讀取數(shù)據(jù)
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)
數(shù)據(jù)重新寫入到 MySQL
數(shù)據(jù)重新寫入 MySQL 使用
pd的to_sql方法
df.to_sql(name=table_name, con=self.conn, if_exists='append', index=True)
pandas 設(shè)置
#顯示所有列
pd.set_option('display.max_columns', None)
#顯示所有行
pd.set_option('display.max_rows', None)
#設(shè)置 value 的顯示長度為 100,默認(rèn)為 50
pd.set_option('max_colwidth',100)
問題
1、pd 的 to_sql 不能使用 pymysql 的連接,否則就會(huì)直接報(bào)錯(cuò)
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 中的數(shù)據(jù)中有空值,但是使用
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)
# 將亂碼替換替換為空字符串(正則為匹配不是中文、字母、數(shù)字組成的字符串)
df['product_name'].replace(r'[^\u4e00-\u9fa5_a-zA-Z0-9]', np.nan, regex=True, inplace=True)評(píng)論
圖片
表情
