前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >技术|数据透视表,Python也可以

技术|数据透视表,Python也可以

作者头像
做数据的二号姬
发布2020-05-22 15:40:52
1.9K0
发布2020-05-22 15:40:52
举报
文章被收录于专栏:HR大数据HR大数据

19

2019-01

技术|数据透视表,Python也可以

对于熟悉Excel的小伙伴来说,学习Python的时候就按照没个功能在Python中如何实现进行学习就可以啦~

LEARN MORE

图片来自网络,如侵删

换工具不换套路

对于习惯于用Excel进行数据分析的我们来说,数据透视表的使用绝对是排名仅次于公式使用的第二大利器。特别是在数据预处理的时候,来一波透视简直是初级得不能再初级的操作了。

我们在开始对一组数据进行分析的时候,进行描述性统计都是必不可少的一步,不管你要用什么精深的算法,使用描述性统计进行数据查错和清洗这个步骤都不能少。

如果换用一个软件,很显然,这样的思路也不会发生任何改变。

接下来就给大家讲一下如何在Python中实现数据透视表的功能。

pivot

pd.pivot_table

这就是实现数据透视表功能的核心函数。显而易见,这个函数也是基于Pandas的。在使用这个功能之前,需要先import pandas as pd哦~

pivot这个单词本身就已经告诉我们这个函数实现的功能类似于数据透视表(数据透视:data pivot)

需要指定的参数也和Excel非常类似,官方的解释如下,这里我复制了比较重要的一部分,感兴趣的可以去试下help(pd.pivot_table): data : DataFrame

values : column to aggregate, optional

index : column, Grouper, array, or list of the previous . If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values. columns : column, Grouper, array, or list of the previous . If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list).Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values. aggfunc : function, list of functions, dict, default numpy.mean . If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) If dict is passed, the key is column to aggregate and value is function or list of functions

fill_value : scalar, default None Value to replace missing values with margins : boolean, default False Add all row / columns (e.g. for subtotal / grand totals)

dropna : boolean, default True Do not include columns whose entries are all NaN

margins_name : string, default 'All' Name of the row / column that will contain the totals when margins is True.

以上就是pivot函数的参数和相关参数的说明,个人人为前面几个参数(data 、values 、index、columns、aggfunc )相对比较重要,接下来会和Excel做对比进行解释和说明。

参数解读

如果单纯解释每个参数是什么意思的话大家可能理解起来就比较费劲了,如果和Excel对比起来说对大家而言理解难度就不大了。

我们先回顾一下使用Excel进行数据透视表的操作过程:

首先,选中希望进行数据透视的数据,点击数据透视表,指定数据透视表的位置。

然后就到了最经典的勾选的部分,Excel给了我们筛选,行,列,值四个选择的地方。

敲黑板,重点来了:

index=列

colums=行

values=值

有了这三个函数,最最最基础的一个数据透视表就算是完成了。

接下来是aggfunc这个函数,相当于我们在Excel中对值进行的这个操作:

fill_value这个参数如果不做定义的话,空缺的数据会以NA的形式出现,所以一般情况下我们指定为0或“”(空)

完整代码

最后给大家一个完整的pd.pivot代码:

data_pivot=pd.pivot_table(data,index=['希望出现在透视表列位置的列名称'],columns=[‘希望出现在透视表列行置的列名称'],values=['希望出现在透视表列行置的值名称'],aggfunc=sum,fill_value=0,margins=True)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 做数据的二号姬 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档