pandas教程:Hierarchical Indexing 分层索引、排序和统计

news/2024/7/19 10:23:23 标签: pandas, python, 开发语言, transformer, requests, 索引, index

文章目录

  • Chapter 8 Data Wrangling: Join, Combine, and Reshape(数据加工:加入, 结合, 变型)
  • 8.1 Hierarchical Indexing(分层索引
  • 1 Reordering and Sorting Levels(重排序和层级排序)
  • 2 Summary Statistics by Level (按层级来归纳统计数据)
  • 3 Indexing with a DataFrame’s columns(利用DataFrame的列来索引

Chapter 8 Data Wrangling: Join, Combine, and Reshape(数据加工:加入, 结合, 变型)

在很多应用中,数据通常散落在不同的文件或数据库中,并不方便进行分析。这一章主要关注工具,能帮我们combine, join, rearrange数据。

8.1 Hierarchical Indexing(分层索引

Hierarchical Indexingpandas中一个重要的特性,能让我们在一个轴(axis)上有多个index levels索引层级)。它可以让我们在低维格式下处理高维数据。这里给出一个简单的例子,构建一个series,其indexa list of lists:

python">import pandas as pd
import numpy as np
python">data = pd.Series(np.random.randn(9),
                 index=[['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'],
                        [1, 2, 3, 1, 3, 1, 2, 2, 3]])
python">data
a  1    0.636082
   2   -1.413061
   3   -0.530704
b  1   -0.041634
   3   -0.042303
c  1    0.429911
   2    0.783350
d  2    0.284328
   3   -0.360963
dtype: float64

其中我们看到的是把MultiIndex作为index(索引)的,美化过后series

python">data.index
MultiIndex(levels=[['a', 'b', 'c', 'd'], [1, 2, 3]],
           labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 2, 0, 1, 1, 2]])

对于这种分层索引对象,partial indexing(部分索引)也是能做到的,这种方法可以让我们简洁地选中数据的一部分:

python">data['b']
1   -0.041634
3   -0.042303
dtype: float64
python">data['b': 'c']
b  1   -0.041634
   3   -0.042303
c  1    0.429911
   2    0.783350
dtype: float64
python">data.loc[['b', 'd']]
b  1   -0.041634
   3   -0.042303
d  2    0.284328
   3   -0.360963
dtype: float64

selection(选中)对于一个内部层级(inner level)也是可能的:

python">data.loc[:, 2]
a   -1.413061
c    0.783350
d    0.284328
dtype: float64

分层索引的作用是改变数据的形状,以及做一些基于组的操作(group-based)比如做一个数据透视表(pivot table)。例子,我们可以用unstack来把数据进行重新排列,产生一个DataFrame

python">data.unstack()
123
a0.636082-1.413061-0.530704
b-0.041634NaN-0.042303
c0.4299110.783350NaN
dNaN0.284328-0.360963

相反的操作是stack:

python">data.unstack().stack()
a  1    0.636082
   2   -1.413061
   3   -0.530704
b  1   -0.041634
   3   -0.042303
c  1    0.429911
   2    0.783350
d  2    0.284328
   3   -0.360963
dtype: float64

之后的章节会对unstackstack做更多介绍。

对于dataframe,任何一个axis(轴)都可以有一个分层索引

python">frame = pd.DataFrame(np.arange(12).reshape((4, 3)),
                     index=[['a', 'a', 'b', 'b'], [1, 2, 1, 2]],
                     columns=[['Ohio', 'Ohio', 'Colorado'],
                              ['Green', 'Red', 'Green']])
frame
OhioColorado
GreenRedGreen
a1012
2345
b1678
291011

每一层级都可以有一个名字(字符串或任何python对象)。如果有的话,这些会显示在输出中:

python">frame.index.names = ['key1', 'key2']
python">frame.columns.names = ['state', 'color']
python">frame
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
2345
b1678
291011

这里我们要注意区分行标签(row label)中索引的名字’state’和’color’。

如果想要选中部分列(partial column indexing)的话,可以选中一组列(groups of columns):

python">frame['Ohio']
colorGreenRed
key1key2
a101
234
b167
2910

MultiIndex能被同名函数创建,而且可以重复被使用;在DataFrame中给列创建层级名可以通过以下方式:

python">pd.MultiIndex.from_arrays([['Ohio', 'Ohio', 'Colorado'], ['Green', 'Red', 'Green']],
                      names=['state', 'color'])
MultiIndex(levels=[['Colorado', 'Ohio'], ['Green', 'Red']],
           labels=[[1, 1, 0], [0, 1, 0]],
           names=['state', 'color'])

1 Reordering and Sorting Levels(重排序和层级排序)

有时候我们需要在一个axis(轴)上按层级进行排序,或者在一个层级上,根据值来进行排序。swaplevel会取两个层级编号或者名字,并返回一个层级改变后的新对象(数据本身并不会被改变):

python">frame.swaplevel('key1', 'key2')
stateOhioColorado
colorGreenRedGreen
key2key1
1a012
2a345
1b678
2b91011

另一方面,sort_index则是在一个层级上,按数值进行排序。比如在交换层级的时候,通常也会使用sort_index,来让结果按指示的层级进行排序:

python">frame.sort_index(level=1)
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
b1678
a2345
b291011
python">frame.sort_index(level='color') 
frame.sort_index(level='state') 
# 这两个语句都会报错

(按照我的理解,level指的是key1key2key1level=0,key2level=1。可以看到下面的结果和上面是一样的:)

python">frame.sort_index(level='key2') 
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
b1678
a2345
b291011
python">frame.swaplevel(0, 1).sort_index(level=0) # 把key1余key2交换后,按key2来排序
stateOhioColorado
colorGreenRedGreen
key2key1
1a012
b678
2a345
b91011

如果index是按词典顺序那种方式来排列的话(比如从外层到内层按a,b,c这样的顺序),在这种多层级的index对象上,数据选择的效果会更好一些。这是我们调用sort_index(level=0) or sort_index()

2 Summary Statistics by Level (按层级来归纳统计数据)

DataFrameSeries中,一些描述和归纳统计数据都是有一个level选项的,这里我们可以指定在某个axis下,按某个level(层级)来汇总。比如上面的DataFrame,我们可以按 行 或 列的层级来进行汇总:

python">frame
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
2345
b1678
291011
python">frame.sum(level='key2')
stateOhioColorado
colorGreenRedGreen
key2
16810
2121416
python">frame.sum(level='color', axis=1)
colorGreenRed
key1key2
a121
284
b1147
22010

3 Indexing with a DataFrame’s columns(利用DataFrame的列来索引

DataFrame里的一列或多列作为行索引row index)是一件很常见的事;另外,我们可能还希望把行索引变为列。这里有一个例子:

python">frame = pd.DataFrame({'a': range(7), 'b': range(7, 0, -1),
                      'c': ['one', 'one', 'one', 'two', 'two',
                            'two', 'two'],
                      'd': [0, 1, 2, 0, 1, 2, 3]})
frame
abcd
007one0
116one1
225one2
334two0
443two1
552two2
661two3

DataFrameset_index会把列作为索引,并创建一个新的DataFrame

python">frame2 = frame.set_index(['c', 'd'])
frame2
ab
cd
one007
116
225
two034
143
252
361

默认删除原先的列,当然我们也可以留着:

python">frame.set_index(['c', 'd'], drop=False)
abcd
cd
one007one0
116one1
225one2
two034two0
143two1
252two2
361two3

另一方面,reset_index的功能与set_index相反,它会把多层级索引变为列:

python">frame2.reset_index()
cdab
0one007
1one116
2one225
3two034
4two143
5two252
6two361

http://www.niftyadmin.cn/n/5159591.html

相关文章

react: scss使用样式

方式一&#xff1a; 将样式作为模块使用 //List.tsx import styles from /styles/apppublish.module.scss <div className{styles.contentOverflow}></div>//apppublish.module.scss .contentOverflow {height: 100%;overflow-y: auto;display: flex;flex-directi…

10.将10个数组的元素依次赋值为0-9,逆序输出

#include<stdio.h>void fun(int a[10]) {int i;printf("后顺序是&#xff1a;") ;for(i9;i>0;i--)printf("%d ",a[i]); }int main(){int i,a[10];printf("原顺序是&#xff1a;") ;for(i0;i<10;i) {a[i]i; printf("%d ",a…

pandas教程:String Manipulation 字符串处理和正则表达式re

文章目录 7.3 String Manipulation&#xff08;字符串处理&#xff09;1 String Object Methods&#xff08;字符串对象方法&#xff09;2 Regular Expressions&#xff08;正则表达式&#xff09;3 Vectorized String Functions in pandas&#xff08;pandas中的字符串向量化函…

什么是Java虚拟机(JVM),它的作用是什么?

什么是Java虚拟机&#xff08;JVM&#xff09; Java虚拟机&#xff08;Java Virtual Machine&#xff0c;JVM&#xff09;是Java平台的关键组成部分&#xff0c;它是一种在不同操作系统上运行Java程序的虚拟计算机。 JVM的作用是执行Java字节码&#xff08;Java bytecode&#…

基础算法-回溯算法-案例

现象&#xff1a; 基础算法-回溯算法-案例 基础算法-回溯算法从不同角度出发 去寻找答案 找到答案或者走不通了(根据需求:找一个答案还是列举全部答案) 则回溯返回继续从下一条路出发 去寻找答案, 一直到走完 常见案例&#xff1a; 案例一&#xff1a; 通过输入一个不重复数…

边玩边学!Python随机生成迷宫游戏的代码简单示例。

文章目录 前言一、生成迷宫的二维数组二、深度优先搜索算法寻找通路三、生成迷宫的随机算法四、使用Pygame显示迷宫五、随机生成迷宫游戏完整代码关于Python技术储备一、Python所有方向的学习路线二、Python基础学习视频三、精品Python学习书籍四、Python工具包项目源码合集①P…

solidworks安装时,出现这个错误:无法获得下列许可SOLIDWORKS Standard.无效的(不一致的)使用许可号码。(-8,544,0)

问题描述&#xff1a;在安装SolidWorks2023时&#xff0c;按照软件管家中的步骤&#xff0c;但是在打开SolidWorks2023桌面上的快捷键时&#xff0c;出现了这个错误&#xff1a; 无法获得下列许可SOLIDWORKS Standard.无效的&#xff08;不一致的&#xff09;使用许可号码。(-…

RabbitMQ(高级特性) 设置队列所有消息存活时间

RabbitMQ可以设置消息的存活时间&#xff08;Time To Live&#xff0c;简称TTL&#xff09;&#xff0c;当消息到达存活时间后还没有被消费&#xff0c;会被移出队列。RabbitMQ可以对队列的所有消息设置存活时间&#xff0c;也可以对某条消息设置存活时间。 Configuration pub…