1. 目的:SQL语句的Pandas实现
数据分析师最基础的技能之一:写SQL统计数据;
然..不够使,又须多一个能力,
数据分析师最基础的技能之一:Pandas数据处理
2. 环境
python2.7
python须安装ipython, pandas, numpy, mysqldb
mysql, 并下载练习包employees database
如果不想花时间搭建环境, 我已经在云端搭建了数据学习环境,按照下面的文章最后的说明,申请远程访问权限:
2019年,数据民工的大白话规划
2.1 练习环境
ipython
import MySQLdb
import pandas as pd
conn = MySQLdb.connect(host='127.0.0.1', user='usertest', passwd='usertest',port=3306, db='employees', charset="utf8")
cur = conn.cursor()
df_employees = pd.read_sql('select * from employees', con=conn)
备注:
python MySQLdb连接数据库,为防止查询结果中文乱码,connect参数注意增加charset="utf8"(因为一般表创建字符charset为utf8)
3. SQL实例
下面开始一步一步对照SQL的统计语句和Pandas实现方法:
3.1 单表查询
3.1.1 查询前几行
sql
select * from emloyees limit 10
pandas
# 方法一:
df_employees.iloc[0:10]
# 方法二:
df_employees.head(10)
3.1.2 查询某个字段
sql
select emp_no, birth_date from emloyees
pandas
df_employees[['emp_no', 'birth_date']]
3.1.3 查询某字段前几行
sql
select emp_no, birth_date from emloyees limit 10
pandas
df_employees[['emp_no', 'birth_date']].iloc[0:10]
df_employees[['emp_no', 'birth_date']].head(10)
3.1.4 单字段筛选特殊值
sql
select * from emloyees where hire_date='1986-06-26'