公众号:尤而小屋
作者:Peter
编辑:Peter
大家好,我是Peter~
本文主题:对比SQL,学习Pandas操作!
在SQL中查询数据的时候我们所有各种操作,主要是通过select、where、group by等多个关键词的组合查询来实现的。本文中介绍的如何在相同的需求下,通过pandas来实现取数操作。

比较方向
- 查询全部数据
- 前N条
- 后N条
- 中间段数据
- 部分字段
- 指定等式条件
- 指定不等式条件
- 取反操作
- 指定多个条件
- 指定计算等式
- 模糊查询
- 排序
- 分组统计
- 取别名
参考资料
因为本文主要介绍的是如何通过pandas来获取我们想要的数据,也是pandas的各种取数技巧,参考之前介绍的3篇文章:
模拟数据
在数据库中,我们先模拟了3份数据:
1、学生信息表
-- 学生信息
mysql> select * from Student;
+------+--------+------------+-------+
| s_id | s_name | s_birth | s_sex |
+------+--------+------------+-------+
| 01 | 赵雷 | 1990-01-01 | 男 |
| 02 | 钱电 | 1990-12-21 | 男 |
| 03 | 孙风 | 1990-05-20 | 男 |
| 04 | 李云 | 1990-08-06 | 男 |
| 05 | 周梅 | 1991-12-01 | 女 |
| 06 | 吴兰 | 1992-03-01 | 女 |
| 07 | 郑竹 | 1989-07-02 | 女 |
| 08 | 王菊 | 1990-01-20 | 女 |
+------+--------+------------+-------+
8 rows in set (0.00 sec)
2、一份用户表

3、一份水果商品价格表

下面开始介绍不同需求下基于pandas和SQL的取数实现
取出全部数据
SQL实现
select * from Student;

Pandas实现

前N条数据
SQL实现
查看前5条数据:


Pandas实现
head方法默认是前5条:

指定查看前7条数据:

后N条数据
select *
from (select * from Student
order by s_id desc
limit 5)t -- 临时结果表:倒序输出的最后5条
order by s_id; -- 再使用一次排序,将顺序还原

Pandas实现
tail方法默认是后5条:

指定查看4条

切片数据
SQL实现

Pandas实现
使用pandas中的切片来查看某个连续区间内的数据:

取出部分字段
SQL实现

Pandas实现
df1[["id","name","sex"]] # 方式1
df2.filter(items=["id","age","createtime"]) # 方式2

指定等式条件
SQL实现


Pandas实现
df1[df1["sex"] == "男"] # 方式1
df1.query('sex=="男"') # 方式2

指定id号或者年龄age:

指定不等式条件
SQL实现
select * from Student where s_sex!= "男";
select * from user where age > 18;
select * from user where id <= 3;

Pandas实现



取反操作
SQL实现
mysql> select * from Student where s_sex != "男";

Pandas实现



指定多个条件
SQL实现
select * from Student where s_birth <="1991-01-01" and s_sex= "男";
select * from user where age < 20 and fee > 60;
select * from user where age < 20 and fee > 60;
Pandas实现

指定计算等式
SQL实现
select * from user where age % 3 = 0; -- 年龄分别是3或者2的倍数
select * from user where age % 2 = 0;

Pandas实现


模糊查询
SQL实现
SQL的关键词是like:
- 左匹配
- 右匹配
- 全匹配

Pandas实现


排序
默认是升序,可以指定为降序
SQL实现
1、单个字段

select * from Student order by s_birth desc; -- 改成升序
2、多个字段的排序

Pandas实现
1、单个字段


2、多个字段

分组统计
SQL实现
通过group by 来进行分组统计:

Pandas实现
先看看df3的数据,一个水果会对应多个价格,我们水果的名称对价格汇总:

df3.groupby("name").agg({"price":"sum"}).reset_index() # 方式1
df3.groupby("name")["price"].sum().reset_index() # 方式2

取别名
SQL实现
通过使用as 关键词:
select name as 水果, sum(price) as 价格 from products group by name;

Pandas实现
Pandas是通过rename函数来实现的:
df3.groupby("name").agg({"price":"sum"}).reset_index().rename(columns={"name":"水果","price":"价格"})

网友评论