数据分析师必学:Series多层级索引与数据操作技巧

在数据分析中,Pandas 的多层级索引(MultiIndex)功能允许用户创建复杂的数据结构,以便更好地组织和分析数据。多层级的 Series 使得在多个维度上进行数据访问和操作变得更加灵活和高效。通过使用类似于 groupby 和 agg 的方法,用户可以轻松地对数据进行分组统计和描述性分析。多掌握多层级的 Series 是进行高级数据分析的重要技能,能够帮助分析师深入挖掘数据中的潜在信息。

1、分层索引

分层索引是 Series 的重要特性,允许你在一个轴向上拥有多个(两个或两个以上)索引层级。笼统地说,分层索引提供了一种在更低维度的形式中处理更高维度数据的方式。如下所示,我们看一个简单的分层索引的 Series 对象

ini 复制代码
import pandas as pd
import numpy as np

data = pd.Series(np.arange(1,10),
                    index=[['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'],
                    ['one', 'two', 'three', 'one', 'three', 'one', 'two', 'two', 'three']])
data

# ---- 输出 ----
# a  one      1
#    two      2
#    three    3
# b  one      4
#    three    5
# c  one      6
#    two      7
# d  two      8
#    three    9
# dtype: int32

我们可以通过 index 属性获取到 Series 对象的索引,如下所示,输出的是一个以 MultiIndex 对象的索引

shell 复制代码
data.index

# ---- 输出 ----
# MultiIndex([('a',   'one'),
#             ('a',   'two'),
#             ('a', 'three'),
#             ('b',   'one'),
#             ('b', 'three'),
#             ('c',   'one'),
#             ('c',   'two'),
#             ('d',   'two'),
#             ('d', 'three')],)

2、多层级数据获取

与 Series 的基本查询一样,我们可以通过 第一层索引 简洁地选择出数据的子集,如下所示

bash 复制代码
data['b']
# ---- 输出 ----
# one      4
# three    5
# dtype: int32

data['b':'c']
# ---- 输出 ----
# b  one      4
#    three    5
# c  one      6
#    two      7
# dtype: int32

data.loc[['b','d']]
# ---- 输出 ----
# b  one      4
#    three    5
# d  two      8
#    three    9
# dtype: int32

当然,我们也能在"内部"层级中进行选择查询数据,如下所示

bash 复制代码
data[:,'two']

# ---- 输出 ----
# a    2
# c    7
# d    8
# dtype: int32

3、多层级数据转换

我们可以使用 unstack 方法将其转换为 DataFrame,如下所示

bash 复制代码
data.unstack()

# ---- 输出 ----
#   one	three two
# a	1.0	3.0	2.0
# b	4.0	5.0	NaN
# c	6.0	NaN	7.0
# d	NaN	9.0	8.0

我们可以使用 stack 将 DataFrame 转化为 Series 对象,如下所示

bash 复制代码
data.unstack().stack()

# ---- 输出 ----
# a  one      1.0
#    three    3.0
#    two      2.0
# b  one      4.0
#    three    5.0
# c  one      6.0
#    two      7.0
# d  three    9.0
#    two      8.0
# dtype: float64

4、重排序和层级排序

如果我们想对层级进行调换,可以使用 swaplevel 接收两个层级序号或层级名称,返回一个进行了层级变更的新对象(但是数据是不变的):

python 复制代码
import pandas as pd
import numpy as np

index = pd.MultiIndex.from_tuples(
    [('a', 'one'), ('a', 'two'), ('a', 'three'), ('b', 'one'), ('b', 'three'),
    ('c', 'one'), ('c', 'two'), ('d', 'two'), ('d', 'three')],
    names=['code', 'num']  # 设置索引名称
)

data = pd.Series(np.arange(1,10), index=index)
data
# ---- 输出 ----
# code  num
# a     one      1
#       two      2
#       three    3
# b     one      4
#       three    5
# c     one      6
#       two      7
# d     two      8
#       three    9
# dtype: int32

data.swaplevel('code', 'num')
# ---- 输出 ----
# num    code
# one    a       1
# two    a       2
# three  a       3
# one    b       4
# three  b       5
# one    c       6
# two    c       7
#        d       8
# three  d       9
# dtype: int32

如果我们想根据层级名称进行排序,我们可以使用 sort_index 可以根据单一层级的名称进行排序。

ini 复制代码
data.sort_index(level=1)

# ---- 输出 ----
# code  num  
# a     one      1
# b     one      4
# c     one      6
# a     three    3
# b     three    5
# d     three    9
# a     two      2
# c     two      7
# d     two      8
# dtype: int32

如果我们想根据数值大小进行排序,我们可以使用 sort_values 可以根据数值大小进行排序。

ini 复制代码
data.sort_values(ascending=False)
# ---- 输出 ----
# code  num  
# d     three    9
#       two      8
# c     two      7
#       one      6
# b     three    5
#       one      4
# a     three    3
#       two      2
#       one      1
# dtype: int32

5、按层级进行汇总统计

Series 中按层级进行描述性和汇总性统计可以通过 groupby 进行汇总,再调用描述性和汇总性统计的方法,如下所示,是多层级进行相加的统计,其它的描述性和汇总性统计的使用类似,我们不再分别赘述。

ini 复制代码
data.groupby(level='code').sum()

# ---- 输出 ----
# code
# a     6
# b     9
# c    13
# d    17
# dtype: int32

如果你喜欢本文,欢迎点赞,并且关注我们的微信公众号:Python技术极客,我们会持续更新分享 Python 开发编程、数据分析、数据挖掘、AI 人工智能、网络爬虫等技术文章!让大家在Python 技术领域持续精进提升,成为更好的自己!

添加作者微信(coder_0101),拉你进入行业技术交流群,进行技术交流~

相关推荐
AI攻城狮1 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健16 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞18 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽20 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
Duang1 天前
从零推导指数估值模型 —— 一个三因子打分系统的设计思路
数据分析·领域驱动设计
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效