层级索引(hierarchical indexing)

下面创建一个Series, 在输入索引Index时,输入了由两个子list组成的list,第一个子list是外层索引,第二个list是内层索引。

示例代码:

import pandas as pd
import numpy as np ser_obj = pd.Series(np.random.randn(12),index=[
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
])
print(ser_obj)

运行结果:

a  0    0.099174
1 -0.310414
2 -0.558047
b 0 1.742445
1 1.152924
2 -0.725332
c 0 -0.150638
1 0.251660
2 0.063387
d 0 1.080605
1 0.567547
2 -0.154148
dtype: float64

MultiIndex索引对象

  • 打印这个Series的索引类型,显示是MultiIndex

  • 直接将索引打印出来,可以看到有lavels,和labels两个信息。lavels表示两个层级中分别有那些标签,labels是每个位置分别是什么标签。

示例代码:

print(type(ser_obj.index))
print(ser_obj.index)

运行结果:

<class 'pandas.indexes.multi.MultiIndex'>
MultiIndex(levels=[['a', 'b', 'c', 'd'], [0, 1, 2]],
labels=[[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]])

选取子集

  • 根据索引获取数据。因为现在有两层索引,当通过外层索引获取数据的时候,可以直接利用外层索引的标签来获取。

  • 当要通过内层索引获取数据的时候,在list中传入两个元素,前者是表示要选取的外层索引,后者表示要选取的内层索引。

1. 外层选取:

ser_obj['outer_label']

示例代码:

# 外层选取
print(ser_obj['c'])

运行结果:

0   -1.362096
1 1.558091
2 -0.452313
dtype: float64

2. 内层选取:

ser_obj[:, 'inner_label']

示例代码:

# 内层选取
print(ser_obj[:, 2])

运行结果:

a    0.826662
b 0.015426
c -0.452313
d -0.051063
dtype: float64

常用于分组操作、透视表的生成等

交换分层顺序

1. swaplevel()

.swaplevel( )交换内层与外层索引。

示例代码:

print(ser_obj.swaplevel())

运行结果:

0  a    0.099174
1 a -0.310414
2 a -0.558047
0 b 1.742445
1 b 1.152924
2 b -0.725332
0 c -0.150638
1 c 0.251660
2 c 0.063387
0 d 1.080605
1 d 0.567547
2 d -0.154148
dtype: float64

交换并排序分层

sortlevel()

.sortlevel( )先对外层索引进行排序,再对内层索引进行排序,默认是升序。

示例代码:

# 交换并排序分层
print(ser_obj.swaplevel().sortlevel())

运行结果:

0  a    0.099174
b 1.742445
c -0.150638
d 1.080605
1 a -0.310414
b 1.152924
c 0.251660
d 0.567547
2 a -0.558047
b -0.725332
c 0.063387
d -0.154148
dtype: float64

最新文章

  1. TypeScript
  2. 网络安全——Base64编码、MD5、SHA1-SHA512、HMAC(SHA1-SHA512)哈希
  3. 60阶单群同构于A5的证明
  4. Warning: Using a password on the command line interface can be insecure.解决办法
  5. CentOS版本选择说明
  6. 在命令行中通过adb shell am broadcast发送广播通知
  7. paper 1:图像特征提取
  8. Smart210学习记录-----中断
  9. mRemote配置
  10. 从零开始PHP学习 - 第一天
  11. Factom(公证通)--基于区块链的存证系统
  12. nyoj 非洲小孩
  13. 通信协议:HTTP、TCP、UDP
  14. Vue.Js初学踩坑
  15. 在 Linux 上搭建IntelliJ IDEA license server服务器
  16. 更优雅地关闭资源 - try-with-resource及其异常抑制
  17. Automation服务器不能创建对象(金税盘)
  18. 2019年学Java开发有优势吗?
  19. ROI
  20. 理解 Linux 的平均负载和性能监控

热门文章

  1. Elasticsearch压缩索引——lucene倒排索引本质是列存储+使用嵌套文档可以大幅度提高压缩率
  2. LeetCode OJ:Search for a Range(区间查找)
  3. PHP获取访问页面HTTP状态码的实现代码
  4. JSP的三大指令
  5. C#调用EasyPusher推送到EasyDarwin流媒体服务器直播方案及示例代码整理
  6. iOS开发之谈谈App应用的架构搭建(推荐给大家看)
  7. go 通过nginx代理后获取用户ip
  8. Andriod部分手机频繁闪退,vivo y55a等,Skipped 62 frames! The application may be doing too much work on its main thread
  9. ORM版,学生管理系统03
  10. HihoCoder 1104 : Suzhou Adventure(树形DP)