数据分析—学会用pandas做多层索引
2020-09-24 本文已影响0人
python与数据分析
【导语】Pandas库的名字来源于3种主要数据结构开头字母的缩写:Panel,Dataframe,Series。其中Series表示一维数据,Dataframe表示二维数据,Panel表示三维数据。当数据高于二维时,一般却不用 Panel 表示,为什么呢?如果不用 Panel,又该怎么做呢?
实际上,当数据高于二维时,我们一般用包含多层级索引的Dataframe进行表示,而不是使用Panel。原因是使用多层级索引展示数据更加直观,操作数据更加灵活,并且可以表示3维,4维乃至任意维度的数据。具体要怎么做呢?下面就从多层级索引的创建、取值与排序等内容教大家一些方法!

一、多层索引的创建
1、(隐式)Series创建索引
直接使⽤index参数创建 在使⽤index参数时,index的值是⼀个列表,其中的元素是多个列表,每个列表就是⼀层索 引,举个栗⼦:
import pandas as pd
# 创建Series索引
s = pd.Series(np.random.randint(0,150,size=6),index=[['a','a','b','b','c','c'],['期中','期末','期中','期末','期中','期末']])
s

我们来看⼀下输出结果:第⼀列的a、b、c是第⼀层的索引,第⼆层的期中、期末是 第⼆层的索引,第三列的就是对应的数据。
2、(隐式)DataFrame创建索引
import numpy as np
da = np.random.randint(100,size=(6,3))
df1 = pd.DataFrame(da,index=[["a","a","b","b","c","c"],["期末","期中","期末","期中","期末","期中"]],
columns=["语文","英语","数学"])
df1

3、(显式) pd.MultiIndex
上面建索引的⽅式写起来很麻烦,我们要写很多重复的内容,所以pandas给我们提供了另⼀ 种⽅式(MultiIndex.from_product() )来构建多层索引
使⽤MultiIndex.from_product()方法构建,⾸先我们把每层需要的索引写⼊到⼀个列表中,将这些列表在存⼊到⼀个新的列表当中,作为 参数传⼊MultiIndex.from_product()方法中,把结果赋值给变量index,那么这个index就 是我们构造好的索引,我们只需要在创建Series的时候传入索引即可
# Series
names=["a","b","c"]
exems=["期中","期末"]
index=pd.MultiIndex.from_product([names,exems])
df = pd.Series(np.random.randint(0,150,size=6),index=index)
df

# DataFrame
names=["a","b","c"]
exems=["期中","期末"]
columns = ["语文","英语","数学"]
index=pd.MultiIndex.from_product([names,exems])
df2 = pd.DataFrame(da,index=index,columns=columns)
df2

4、(显式) set_index
# 方法将普通列转成多层级索引
da = np.random.randint(100,size=(6,3))
dic = {"class":["class1","class1","class2","class3"],
"name":["linda","mark","lily","cherich"],
"score":[100,123,120,116]}
df3 = pd.DataFrame(dic)
df3.set_index(["class","name"])

5、(显式)groupby
# 用来聚合计算,比如mean
df3.groupby(['class','name']).mean()

6、(显式)pivot_table
# 类似于excel的透视表,数据动态排布,分类汇总
df3.pivot_table(index=["class","name"])

二、多层索引的取值
1.直接提取[]
# 取单个值
df["a"]

df["a","期中"]
结果:69
# 取多个不连续值
df[["a","c"]]

# 取多个连续的值
df[:"b"]

2、标签取值 loc[], loc 按自定义的行、列的数据进行取值,不遵循左闭右开
# 取单个值
df.loc[:"a"]
# 取多个不连续值
df.loc[["a","c"]]
# 取多个连续的值
df.loc[:"b"]

3、下标取值 iloc[], iloc 按默认的行、列索引的数据进行取值
# 取一个值
df4.iloc[0,3]
# 取多个值
df4.iloc[0,[3,5]]
# 取连续值 遵循左闭右开
df4.iloc[0:1,3:5]

三、多层索引的排序
1、按照索引排序,sort_index()
- level=0 表示按照第⼀层索引进⾏排序,默认为0,为1表示优先按照第⼆层索引 ...
- ascending=False 表示从⼤到⼩进⾏排列,默认为True(从⼩到⼤排序)
names=[1,2,3]
exems=["a","b"]
index=pd.MultiIndex.from_product([names,exems])
data1 = pd.Series([89,53,56,89,78,90],index=index)
# level = 0 则按照第一层索引排序 1 按照第二层
# ascending=False 降序 大到小 True 从小到大
data1.sort_index(level=0,ascending=False)

2、按照具体值(列名)排序,sort_value()
# series
data1.sort_values(ascending=False)
# dataFrame
df1.sort_values(by="语文",ascending=False)

多层索引的应用场景一般是在数据量比较大,字段比较多,逻辑相对复杂的情况下,用来汇总数据,查找数据时使用。
希望本文的内容对大家的学习或者工作能带来一定的帮助,每天进步一点点,加油~