数据分析师必学: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),拉你进入行业技术交流群,进行技术交流~

相关推荐
谷粒.6 分钟前
测试数据管理难题的7种破解方案
运维·开发语言·网络·人工智能·python
数据智研16 分钟前
【数据分享】腾格里沙漠空间矢量范围
大数据·信息可视化·数据分析
寒山李白23 分钟前
关于Python版本与supervisor版本的兼容性
windows·python·supervisord
梨落秋霜38 分钟前
Python入门篇【基础语法】
开发语言·python
ada7_1 小时前
LeetCode(python)——543.二叉树的直径
数据结构·python·算法·leetcode·职场和发展
小白学大数据1 小时前
Python 多线程爬取社交媒体品牌反馈数据
开发语言·python·媒体
HAPPY酷1 小时前
压缩文件格式实战速查表 (纯文本版)
python
祝余Eleanor2 小时前
Day 31 类的定义和方法
开发语言·人工智能·python·机器学习
背心2块钱包邮2 小时前
第6节——微积分基本定理(Fundamental Theorem of Calculus,FTC)
人工智能·python·机器学习·matplotlib
larance2 小时前
修改jupyterlab 默认路径
python