Python数据处理小技巧:pivot_table后如何拍平columns
机器学习的过程中很多时候需要用到类似透视表的功能。Pandas提供了pivot和pivot_table实现透视表功能。相对比而言,pivot_table更加强大,在实现透视表的时候可以进行聚类等操作。
pivot_table帮助地址:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html
官方给的几个例子:
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
... "bar", "bar", "bar", "bar"],
... "B": ["one", "one", "one", "two", "two",
... "one", "one", "two", "two"],
... "C": ["small", "large", "large", "small",
... "small", "large", "small", "small",
... "large"],
... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
... "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
df
A B C D E
0 foo one small 1 2
1 foo one large 2 4
2 foo one large 2 5
3 foo two small 3 5
4 foo two small 3 6
5 bar one large 4 6
6 bar one small 5 8
7 bar two small 6 9
8 bar two large 7 9
This first example aggregates values by taking the sum.
table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
table
C large small
A B
bar one 4.0 5.0
two 7.0 6.0
foo one 4.0 1.0
two NaN 6.0
We can also fill missing values using the fill_value parameter.
table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum, fill_value=0)
table
C large small
A B
bar one 4 5
two 7 6
foo one 4 1
two 0 6
The next example aggregates by taking the mean across multiple columns.
table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': np.mean})
table
D E
A C
bar large 5.500000 7.500000
small 5.500000 8.500000
foo large 2.000000 4.500000
small 2.333333 4.333333
We can also calculate multiple types of aggregations for any given value column.
table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
... aggfunc={'D': np.mean,
... 'E': [min, max, np.mean]})
table
D E
mean max mean min
A C
bar large 5.500000 9.0 7.500000 6.0
small 5.500000 9.0 8.500000 8.0
foo large 2.000000 5.0 4.500000 4.0
small 2.333333 6.0 4.333333 2.0
现在的一个问题是,处理后的dataframe的columns是多层的,例如最后一个例子的columns是这个样子的:
table.columns:
MultiIndex(levels=[['D', 'E'], ['max', 'mean', 'min']],
labels=[[0, 1, 1, 1], [1, 0, 1, 2]])
为了后续的运算,我们经常希望它能简化,便于处理。也就是说吧columns拍平。大家可以这么处理:
table.columns =[s1 +'_'+ str(s2) for (s1,s2) in table.columns.tolist()]
table.reset_index(inplace=True)
效果如下:
table.columns
Index(['A', 'C', 'D_mean', 'E_max', 'E_mean', 'E_min'], dtype='object')
效果如图:

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
Python机器学习小技巧:GroupBy 和 Shift实现 Pandas分组错位
使用Pandas进行数据操作的时候,有时需要分组将数据错位进行操作。 在数据分析中经常遇到需要分组使用a列的第n行数据与去b列的第n+1行数据进行对比或者计算的要求,下面是我使用pandas解决该问题的方法。首先要说的试这个问题可以通过操作Index来实现。不过Pandas针对这种情况已经提供了一种方法了,就是shift函数,用起来更加方便。shift函数定义如下: pandas.DataFrame.shift DataFrame.shift(self,periods=1,freq=None,axis=0,fill_value=None)[source] Shift index by desired number of periods with an optional time freq. When freq is not passed, shift the index without realigning the data. If freq is passed (in this case, the index must be date or datetime, or it will ...
-
下一篇
【网站搭建】阿里云服务器搭建个人网站详细流程
1. 工具的选择 因为直接网页操作实例的话不是很方便,鉴于有Linux和大数据开发经验。使用以下工具 winscp:文件传输,可以实现本地和远程端的文件传输,也可以直接修改远程端文件,不用在终端里了 XSHELL:安全终端模拟软件,可以连接远程操作终端命令 2. 购买 购买的9.9学生价的centos6.5 ecs服务器有Windows和Linux可选,一般选择Linux(我选择的centos)。可以在 磁盘设置 更换 1 2 安全组 购买后在控制台可查看实例信息,首先需要修改安全组策略。 在服务器-实例页面相应实例上点击管理进入,点击配置规则 出入方向都要配置,我的配置如下 说明:安全组规则也就是默认一些端口是关闭的或者说只有该实例有权访问,需要人为打开权限。如授权对象下的IP:0.0.0.0/0就是所有都可以访问,这个酌情配置 声明:阿里云官网目前可以领取2000元产品代金券,领取后可在官网买云产品时,获得金额减免,领取地址:https://www.aliyun.com/minisite/goods?userCode=28kqeewo ; 本地通过公网ip连接时连不上也ping不通...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- SpringBoot2编写第一个Controller,响应你的http请求并返回结果
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- SpringBoot2整合Redis,开启缓存,提高访问速度
- CentOS7编译安装Gcc9.2.0,解决mysql等软件编译问题
- Docker快速安装Oracle11G,搭建oracle11g学习环境
- MySQL数据库在高并发下的优化方案
- MySQL8.0.19开启GTID主从同步CentOS8
- SpringBoot2全家桶,快速入门学习开发网站教程
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- Docker使用Oracle官方镜像安装(12C,18C,19C)