公众号:尤而小屋 作者:Peter 编辑:Peter
大家好,我是Peter~
本文主题:对比SQL,学习Pandas操作!
在SQL中查询数据的时候我们所有各种操作,主要是通过select、where、group by等多个关键词的组合查询来实现的。本文中介绍的如何在相同的需求下,通过pandas来实现取数操作。
<!--MORE-->
因为本文主要介绍的是如何通过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的取数实现
select * from Student;
查看前5条数据:
head方法默认是前5条:
指定查看前7条数据:
select *
from (select * from Student
order by s_id desc
limit 5)t -- 临时结果表:倒序输出的最后5条
order by s_id; -- 再使用一次排序,将顺序还原
tail方法默认是后5条:
指定查看4条
使用pandas中的切片来查看某个连续区间内的数据:
df1[["id","name","sex"]] # 方式1
df2.filter(items=["id","age","createtime"]) # 方式2
df1[df1["sex"] == "男"] # 方式1
df1.query('sex=="男"') # 方式2
指定id号或者年龄age:
select * from Student where s_sex!= "男";
select * from user where age > 18;
select * from user where id <= 3;
mysql> select * from Student where s_sex != "男";
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;
select * from user where age % 3 = 0; -- 年龄分别是3或者2的倍数
select * from user where age % 2 = 0;
SQL的关键词是like:
默认是升序,可以指定为降序
1、单个字段
select * from Student order by s_birth desc; -- 改成升序
2、多个字段的排序
1、单个字段
2、多个字段
通过group by 来进行分组统计:
先看看df3的数据,一个水果会对应多个价格,我们水果的名称对价格汇总:
df3.groupby("name").agg({"price":"sum"}).reset_index() # 方式1
df3.groupby("name")["price"].sum().reset_index() # 方式2
通过使用as 关键词:
select name as 水果, sum(price) as 价格 from products group by name;
Pandas是通过rename函数来实现的:
df3.groupby("name").agg({"price":"sum"}).reset_index().rename(columns={"name":"水果","price":"价格"})
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。