Pandas 教程:数据处理基石 - 数据探索

公众号:尤而小屋<br>作者:Peter<br>编辑:Peter
大家好,我是 Peter~
本文介绍的是 Pandas 数据初探索。当我们生成或者导入了数据之后,通过数据的探索工作能够快速了解和认识数据基本信息,比如数据中字段的类型、索引、最值、缺失值等,可以让我们对数据的全貌有一个初步了解。

思维导图

模拟数据
本文中的方法介绍使用的是一份模拟数据,有字符型、数值型,还有时间类型;同时数据刻意存在了缺失值:

使用 pandas 的 read_excel 方法对数据进行读取:

同时生成一个 Series 类型数据:

数据样本
头尾数据查看
head(N):默认是头部 5 条,可以指定查看 N 条
tail(N):默认是尾部 5 条,可以指定查看 N 条

随机查看 sample
默认是随机看一条数据,也可以指定查看的条数:

查看数据形状 shape
在这里的形状指的是数据有多少行和多少列,通过查看数据的 shape 就能知道数据的大小
DataFrame 类型:两个数值,表示行和列
Series 类型:只有行数

数据大小 size
数据大小表示的是数据中总共有多少个数据,即 shape 方法的结果中两个数值相乘
数据维度 ndim
表示数据是多少维,比如二维,三维等

数据基本信息 info
显示数据类型、索引情况、行列数、列属性名称、占用的内存等信息;Series 数据没有该方法

数据类型 dtypes

列属性和行索引
通过 axes 来查看;DataFrame 数据既有行索引也有列名,Series 数据只有行索引。

查看行索引
通过专门的 index 属性来查看行索引

查看列属性

查看数据
两个方法或属性查看:
values
to_numpy()

查看缺失值
在数据帧中如果存在缺失值,则用 True 表示,否则取值为 False:

查看内存情况 memory_usage()
查看每列的内存使用情况,以字节为单位:

统计信息
描述信息只针对数值型的数据,可以看到该字段中数据的统计值信息
整体信息 describe
返回的是数值型数据中的个数、均值、方差、四分位数等统计值情况

查看均值
一般 DataFrame 计算后为一个 Series,Series 计算后是一个具体的数值
下面的代码是按照列来计算均值:
查看某个列的均值:
下面的代码是按照行来计算均值:

Pandas 内置数学计算方法
Pandas 中内置的多种数学计算函数
总结
本文主要是对 Pandas 中的数据探索做了一个详细介绍,帮助我们快速了解数据的基本信息,同时也方便后续的数据处理和分析。
版权声明: 本文为 InfoQ 作者【Peter】的原创文章。
原文链接:【http://xie.infoq.cn/article/1004e42154692df81c9aa5225】。文章转载请联系作者。
评论