数据分析之PandasVSSQL!
编辑:zone
按需开发可以根据自己的需求进行定制,成都网站设计、网站制作构思过程中功能建设理应排到主要部位公司成都网站设计、网站制作的运用实际效果公司网站制作网站建立与制做的实际意义
来源:数据管道
作者:艾德宝器
Abstract
Pandas是一个开源的Python数据分析库,结合 NumPy 和 Matplotlib 类库,可以在内存中进行高性能的数据清洗、转换、分析及可视化工作。
对于数据开发工程师或分析师而言,SQL 语言是标准的数据查询工具。本文提供了一系列的示例,说明如何使用pandas执行各种SQL操作。
Pandas简介
Pandas把结构化数据分为了三类:
Series,可以理解为一个一维的数组,只是index可以自己改动。
DataFrame,一个类似于表格的数据类型的2维结构化数据。
Panel,3维的结构化数据。
Dataframe实例:

对于DataFrame,有一些固有属性:

SQL VS Pandas
SELECT(数据选择)
在SQL中,选择是使用逗号分隔的列列表(或*来选择所有列):

在Pandas中,选择不但可根据列名称选取,还可以根据列所在的位置选取。相关语法如下:
loc,基于列label,可选取特定行(根据行index)
iloc,基于行/列的位置
ix,为loc与iloc的混合体,既支持label也支持position
at,根据指定行index及列label,快速定位DataFrame的元素;
iat,与at类似,不同的是根据position来定位的;



WHERE(数据过滤)
在SQL中,过滤是通过WHERE子句完成的:

在pandas中,Dataframe可以通过多种方式进行过滤,最直观的是使用布尔索引:

在where子句中常常会搭配and, or, in, not关键词,Pandas中也有对应的实现:
SQL:

Pandas:

在where字句中搭配NOT NULL可以获得某个列不为空的项,Pandas中也有对应的实现:
SQL:

Pandas:

DISTINCT(数据去重)
SQL:

Pandas:

宝器带你画重点:
subset,为选定的列做数据去重,默认为所有列;
keep,可选择{'first', 'last', False},保留重复元素中的第一个、最后一个,或全部删除;
inplace ,Pandas 中 inplace 参数在很多函数中都会有,它的作用是:是否在原对象基础上进行修改,默认为False,返回一个新的Dataframe;若为True,不创建新的对象,直接对原始对象进行修改。
GROUP BY(数据分组)
groupby()通常指的是这样一个过程:我们希望将数据集拆分为组,应用一些函数(通常是聚合),然后将这些组组合在一起:

常见的SQL操作是获取数据集中每个组中的记录数。

Pandas中对应的实现:

注意,在Pandas中,我们使用size()而不是count()。这是因为count()将函数应用于每个列,返回每个列中的非空记录的数量。具体如下:

还可以同时应用多个函数。例如,假设我们想要查看每个星期中每天的小费金额有什么不同。
SQL:

Pandas:

更多关于Groupy和数据透视表内容请阅读:
这些祝福和干货比那几块钱的红包重要的多!
JOIN(数据合并)
可以使用join()或merge()执行连接。
默认情况下,join()将联接其索引上的DataFrames。
每个方法都有参数,允许指定要执行的连接类型(LEFT, RIGHT, INNER, FULL)或要连接的列(列名或索引)

现在看一下不同的连接类型的SQL和Pandas实现:
INNER JOIN
SQL:

Pandas:

LEFT OUTER JOIN
SQL:

Pandas:

RIGHT JOIN
SQL:

Pandas:

FULL JOIN
SQL:

Pandas:

ORDER(数据排序)
SQL:

Pandas:

UPDATE(数据更新)
SQL:

Pandas:

DELETE(数据删除)
SQL:

Pandas:

总结:
本文从Pandas里面基本数据结构Dataframe的固定属性开始介绍,对比了做数据分析过程中的一些常用SQL语句的Pandas实现。
参考:
http://m.v.qq.com/play/play.htmlcoverid=&vid=q0836f6kewx&ptag=4_6.7.0.22106_qq
本文名称:数据分析之PandasVSSQL!
文章来源:http://ybzwz.com/article/ghsphh.html