Python pandas轴旋转stack和unstack的使用说明
作者:Asher117 发布时间:2021-08-10 21:18:34
摘要
前面给大家分享了pandas做数据合并的两篇[pandas.merge]和[pandas.cancat]的用法。今天这篇主要讲的是pandas的DataFrame的轴旋转操作,stack和unstack的用法。
首先,要知道以下五点:
1.stack:将数据的列“旋转”为行
2.unstack:将数据的行“旋转”为列
3.stack和unstack默认操作为最内层
4.stack和unstack默认旋转轴的级别将会成果结果中的最低级别(最内层)
5.stack和unstack为一组逆运算操作
第一点和第二点以及第五点比较好懂,可能乍看第三点和第四点会不太理解,没关系,看看具体下面的例子,你就懂了。
1、创建DataFrame,行索引名为state,列索引名为number
import pandas as pd
import numpy as np
data = pd.DataFrame(np.arange(6).reshape((2,3)),index=pd.Index(['Ohio','Colorado'],name='state')
,columns=pd.Index(['one','two','three'],name='number'))
data
2、将DataFrame的列旋转为行,即stack操作
result = data.stack()
result
从下图中结果来理解上述点4,stack操作后将列索引number旋转为行索引,并且置于行索引的最内层(外层为索引state),也就是将旋转轴(number)的结果置于 最低级别。
3、将DataFrame的行旋转为列,即unstack操作
result.unstack()
从下面结果理解上述点3,unstack操作默认将内层索引number旋转为列索引。
同时,也可以指定分层级别或者索引名称来指定操作级别,下面做错同样会得到上面的结果。
4、stack和unstack逆运算
s1 = pd.Series([0,1,2,3],index=list('abcd'))
s2 = pd.Series([4,5,6],index=list('cde'))
data2 = pd.concat([s1,s2],keys=['one','two'])
data2
data2.unstack().stack()
补充:使用Pivot、Pivot_Table、Stack和Unstack等方法在Pandas中对数据变形(重塑)
Pandas是著名的Python数据分析包,这使它更容易读取和转换数据。在Pandas中数据变形意味着转换表或向量(即DataFrame或Series)的结构,使其进一步适合做其他分析。在本文中,小编将举例说明最常见的一些Pandas重塑功能。
一、Pivot
pivot函数用于从给定的表中创建出新的派生表,pivot有三个参数:索引、列和值。具体如下:
def pivot_simple(index, columns, values):
"""
Produce 'pivot' table based on 3 columns of this DataFrame.
Uses unique values from index / columns and fills with values.
Parameters
----------
index : ndarray
Labels to use to make new frame's index
columns : ndarray
Labels to use to make new frame's columns
values : ndarray
Values to use for populating new frame's values
作为这些参数的值需要事先在原始的表中指定好对应的列名。然后,pivot函数将创建一个新表,其行和列索引是相应参数的唯一值。我们一起来看一下下面这个例子:
假设我们有以下数据:
我们将数据读取进来:
from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np
data = OrderedDict((
("item", ['Item1', 'Item1', 'Item2', 'Item2']),
('color', ['red', 'blue', 'red', 'black']),
('user', ['1', '2', '3', '4']),
('bm', ['1', '2', '3', '4'])
))
data = DataFrame(data)
print(data)
得到结果为:
item color user bm
0 Item1 red 1 1
1 Item1 blue 2 2
2 Item2 red 3 3
3 Item2 black 4 4
接下来,我们对以上数据进行变形:
df = data.pivot(index='item', columns='color', values='user')
print(df)
得到的结果为:
color black blue red
item
Item1 None 2 1
Item2 4 None 3
注意:可以使用以下方法对原始数据和转换后的数据进行等效查询:
# 原始数据集
print(data[(data.item=='Item1') & (data.color=='red')].user.values)
# 变换后的数据集
print(df[df.index=='Item1'].red.values)
结果为:
['1']
['1']
在以上的示例中,转化后的数据不包含bm的信息,它仅包含我们在pivot方法中指定列的信息。下面我们对上面的例子进行扩展,使其在包含user信息的同时也包含bm信息。
df2 = data.pivot(index='item', columns='color')
print(df2)
结果为:
user bm
color black blue red black blue red
item
Item1 None 2 1 None 2 1
Item2 4 None 3 4 None 3
从结果中我们可以看出:Pandas为新表创建了分层列索引。我们可以用这些分层列索引来过滤出单个列的值,例如:使用df2.user可以得到user列中的值。
二、Pivot Table
有如下例子:
data = OrderedDict((
("item", ['Item1', 'Item1', 'Item1', 'Item2']),
('color', ['red', 'blue', 'red', 'black']),
('user', ['1', '2', '3', '4']),
('bm', ['1', '2', '3', '4'])
))
data = DataFrame(data)
df = data.pivot(index='item', columns='color', values='user')
得到的结果为:
ValueError: Index contains duplicate entries, cannot reshape
因此,在调用pivot函数之前,我们必须确保我们指定的列和行没有重复的数据。如果我们无法确保这一点,我们可以使用pivot_table这个方法。
pivot_table方法实现了类似pivot方法的功能,它可以在指定的列和行有重复的情况下使用,我们可以使用均值、中值或其他的聚合函数来计算重复条目中的单个值。
首先,我们先来看一下pivot_table()这个方法:
def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
fill_value=None, margins=False, dropna=True,
margins_name='All'):
"""
Create a spreadsheet-style pivot table as a DataFrame. The levels in the
pivot table will be stored in MultiIndex objects (hierarchical indexes) on
the index and columns of the result DataFrame
Parameters
----------
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 or list of functions, 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)
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.
接下来我们来看一个示例:
data = OrderedDict((
("item", ['Item1', 'Item1', 'Item1', 'Item2']),
('color', ['red', 'blue', 'red', 'black']),
('user', ['1', '2', '3', '4']),
('bm', ['1', '2', '3', '4'])
))
data = DataFrame(data)
df = data.pivot_table(index='item', columns='color', values='user', aggfunc=np.min)
print(df)
结果为:
color black blue red
item
Item1 None 2 1
Item2 4 None None
实际上,pivot_table()是pivot()的泛化,它允许在数据集中聚合具有相同目标的多个值。
三、Stack/Unstack
事实上,变换一个表只是堆叠DataFrame的一种特殊情况,假设我们有一个在行列上有多个索引的DataFrame。堆叠DataFrame意味着移动最里面的列索引成为最里面的行索引,反向操作称之为取消堆叠,意味着将最里面的行索引移动为最里面的列索引。例如:
from pandas import DataFrame
import pandas as pd
import numpy as np
# 建立多个行索引
row_idx_arr = list(zip(['r0', 'r0'], ['r-00', 'r-01']))
row_idx = pd.MultiIndex.from_tuples(row_idx_arr)
# 建立多个列索引
col_idx_arr = list(zip(['c0', 'c0', 'c1'], ['c-00', 'c-01', 'c-10']))
col_idx = pd.MultiIndex.from_tuples(col_idx_arr)
# 创建DataFrame
d = DataFrame(np.arange(6).reshape(2,3), index=row_idx, columns=col_idx)
d = d.applymap(lambda x: (x // 3, x % 3))
# Stack/Unstack
s = d.stack()
u = d.unstack()
print(s)
print(u)
得到的结果为:
c0 c1
r0 r-00 c-00 (0, 0) NaN
c-01 (0, 1) NaN
c-10 NaN (0, 2)
r-01 c-00 (1, 0) NaN
c-01 (1, 1) NaN
c-10 NaN (1, 2)
c0 c1
c-00 c-01 c-10
r-00 r-01 r-00 r-01 r-00 r-01
r0 (0, 0) (1, 0) (0, 1) (1, 1) (0, 2) (1, 2)
实际上,Pandas允许我们在索引的任何级别上堆叠/取消堆叠。 因此,在前面的示例中,我们也可以堆叠在最外层的索引级别上。 但是,默认(最典型的情况)是在最里面的索引级别进行堆叠/取消堆叠。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/Asher117/article/details/85047899


猜你喜欢
- 一. 布隆过滤器简介布隆过滤器可以用于检索一个元素是否在一个集合中。它的优点是空间效率和查询时间都比一般的算法要好的多,缺点是有一定的误识别
- Environs是解析环境变量的Python库。它的开发受envparse启发,底层使用marshmallow验证并序列化值。在运行一个项目
- 现在很多地方都需要用到关键词过滤功能。比如一般的服务器都不允许一些词出现在网页上,站长有时候会对在本网站发布信息的内容进行一个广告过滤等。雨
- 介绍在本文中,你将学习如何使用 Python 构建人脸识别系统。人脸识别比人脸检测更进一步。在人脸检测中,我们只检测人脸在图像中的位置,但在
- 本文实例讲述了python基于urllib实现按照百度音乐分类下载mp3的方法。分享给大家供大家参考。具体实现方法如下:#!/usr/bin
- 先来看查看效果:在代码连接数据库后,并且执行三条sql后,将mysql直接重启掉,故我们的连接池连接均是不ok的,所以,它会全部删除再抓新的
- 代码如下:from PIL import Image #图像处理模块import numpy as npa = np.asarr
- 因为要牵扯到小计,所以需要计算两次。想法:1、把查询到的结果,插入到临时表,2、把统计结果插入到临时表。3、查询临时表记录放置到游标中。4、
- 目录1. 为什么选择Playwright1.1 Playwright的优势1.2 已知局限性2. Playwright使用2.1 安装2.2
- 下面一段代码给大家分享js实现时钟滴答声功能,具体代码如下所示:<!DOCTYPE html><html> <
- 按照正常的产品逻辑,我们在进行页面切换时滚动条应该是在页面顶部的,可是。。。在使用vue-router进行页面切换时,发现滚动条所处的位置被
- 创建main.py文件并粘贴下面代码点击右键运行Debug 'main'后,下方的Debug窗口会出现ImportError
- declare @Table_name varchar(60) set @Table_name = 'Pay_inputpay
- 第一次用Python写这种比较实用且好玩的东西,权当练手吧游戏说明:* P键控制“暂停/开始”* 方向键控制贪吃蛇的方向源代码如下:from
- 1. 原理利用 PIL 库来获取图片并修改大小,利用灰度值转换公式把每一个像素的 RGB 值转为灰度值gray = int(0.2126*r
- 1、拆箱>>> a, b, c = 1, 2, 3>>> a, b, c(1, 2, 3)>>
- 1.执行cmd命令,不显示执行过程中弹出的黑框def run_cmd( cmd_str='', echo_print=1):
- 简介这篇宏哥就带着小伙伴们分享一下如何连接模拟器(电脑版的虚拟手机),然后再安装一款APP-淘宝为例。一、appium+pycharm+连接
- 在机房收费系统中,有几处这样的情况:起始日期和终止日期,相信聪明的你肯定可以想象出为什么要有两个日期控件!是的,就是从一张表中查找出在这两个
- phpinfo() 功能描述:输出 PHP 环境信息以及相关的模块、WEB 环境等信息。 危险等级:中 passthru() 功能描述:允许