Pandas库07_层次化索引
Posted yiyea
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pandas库07_层次化索引相关的知识,希望对你有一定的参考价值。
import numpy as np
import pandas as pd
t_data=
"name":["唐浩","小王","老王","赵三","李四","王姐"],
"sex":["男","女","男","女","男","女"],
"year":[37,22,15,18,33,25],
"city":["成都","北京","上海","成都","深圳","北京"]
#pd.Series对象
# pds1=pd.Series([1,2,3,4,5,6,7,8,9],index=[["X","X","X","Y","Y","Y","Z","Z","Z"],["a","b","c","a","b","c","a","b","c"]])
# print(pds1) #即一维数组或列表带两层索引标签
"""
X a 1
b 2
c 3
Y a 4
b 5
c 6
Z a 7
b 8
c 9
"""
# print(pds1["X"]["b"]) #访问,【前一层】【后二层】
# print(pds1["X","c"]) #访问,【前一层,后二层】
# print(pds1[:,"b"]) #最外层切片可用
# # print(pds1[:]["b"]) #第一层切片不能这样得到
# print(pds1["Y"]) #第二层切片不可用,但只要给出最外层,第二层默认是全部
# print(pds1["Y"][0:2]) #第二层切片可以这样操作得到
# print(pds1.index)
"""
MultiIndex([(‘X‘, ‘a‘),
(‘X‘, ‘b‘),
(‘X‘, ‘c‘),
(‘Y‘, ‘a‘),
(‘Y‘, ‘b‘),
(‘Y‘, ‘c‘),
(‘Z‘, ‘a‘),
(‘Z‘, ‘b‘),
(‘Z‘, ‘c‘)],
)
"""
#DataFrame对象
# pddf1=pd.DataFrame(t_data,index=[["A","A","A","B","B","B"],[1,2,3,1,2,3]])
# print(pddf1)
"""
name sex year city
A 1 唐浩 男 37 成都
2 小王 女 22 北京
3 老王 男 15 上海
B 1 赵三 女 18 成都
2 李四 男 33 深圳
3 王姐 女 25 北京
"""
pddf2=pd.DataFrame(np.arange(10,26).reshape(4,4),index=[["A","A","B","B"],[1,2,1,2]],columns=[["左二","左二","右二","右二"],["a","b","a","b"]])
print(pddf2)
"""
左二 右二
a b a b
A 1 10 11 12 13
2 14 15 16 17
B 1 18 19 20 21
2 22 23 24 25
"""
以上是关于Pandas库07_层次化索引的主要内容,如果未能解决你的问题,请参考以下文章