pd.MultiIndex,即具有多個層次的索引。透過多層次索引,我們就可以操作整個索引組的資料。本文主要介紹在Pandas中建立多層索引的6種方式:
pd.MultiIndex.from_arrays():多維數組作為參數,高維度指定高層索引,低維指定低層索引。
pd.MultiIndex.from_tuples():元組的清單作為參數,每個元組指定每個索引(高維和低維索引)。
pd.MultiIndex.from_product():可迭代物件的列表作為參數,根據多個可迭代物件元素的笛卡爾積(元素間的兩兩組合)進行創建索引。
pd.MultiIndex.from_frame:根據現有的資料框來直接產生
groupby():透過資料分組統計量得到
pivot_table():產生透視表的方式來得到
In [1] :
import pandas as pd import numpy as np
透過陣列的方式來生成,通常指定的是清單中的元素:
In [2]:
# 列表元素是字符串和数字 array1 = [["xiaoming","guanyu","zhangfei"], [22,25,27] ] m1 = pd.MultiIndex.from_arrays(array1) m1
Out[2]:
MultiIndex([('xiaoming', 22), ( 'guanyu', 25), ('zhangfei', 27)], )
In [3]:
type(m1) # 查看数据类型
透過type函數來查看資料類型,發現的確是:MultiIndex
Out[3]:
pandas.core.indexes.multi.MultiIndex
在建立的同時可以指定每個層級的名字:
In [4]:
# 列表元素全是字符串 array2 = [["xiaoming","guanyu","zhangfei"], ["male","male","female"] ] m2 = pd.MultiIndex.from_arrays( array2, # 指定姓名和性别 names=["name","sex"]) m2
Out[4]:
MultiIndex([('xiaoming', 'male'), ( 'guanyu', 'male'), ('zhangfei', 'female')], names=['name', 'sex'])
下面的範例是產生3個層次的索引且指定名字:
In [5]:
array3 = [["xiaoming","guanyu","zhangfei"], ["male","male","female"], [22,25,27] ] m3 = pd.MultiIndex.from_arrays( array3, names=["姓名","性别","年龄"]) m3
Out[5]:
MultiIndex([('xiaoming', 'male', 22), ( 'guanyu', 'male', 25), ('zhangfei', 'female', 27)], names=['姓名', '性别', '年龄'])
透過元組的形式來產生多層索引:
In [6]:
# 元组的形式 array4 = (("xiaoming","guanyu","zhangfei"), (22,25,27) ) m4 = pd.MultiIndex.from_arrays(array4) m4
Out[6]:
MultiIndex([('xiaoming', 22), ( 'guanyu', 25), ('zhangfei', 27)], )
In [7]:
# 元组构成的3层索引 array5 = (("xiaoming","guanyu","zhangfei"), ("male","male","female"), (22,25,27)) m5 = pd.MultiIndex.from_arrays(array5) m5
Out [7]:
MultiIndex([('xiaoming', 'male', 22), ( 'guanyu', 'male', 25), ('zhangfei', 'female', 27)], )
#最外層是列表
array6 = [("xiaoming","guanyu","zhangfei"), ("male","male","female"), (18,35,27) ] # 指定名字 m6 = pd.MultiIndex.from_arrays(array6,names=["姓名","性别","年龄"]) m6
MultiIndex([('xiaoming', 'male', 18), ( 'guanyu', 'male', 35), ('zhangfei', 'female', 27)], names=['姓名', '性别', '年龄'] # 指定名字 )
isinstance()函數來判斷python物件是否可迭代:
# 导入 collections 模块的 Iterable 对比对象 from collections import Iterable
#透過上面的例子我們總結:常見的字串、列表、集合、元組、字典都是可迭代物件下面舉例來說明:In [18 ]:
names = ["xiaoming","guanyu","zhangfei"] numbers = [22,25] m7 = pd.MultiIndex.from_product( [names, numbers], names=["name","number"]) # 指定名字 m7
MultiIndex([('xiaoming', 22), ('xiaoming', 25), ( 'guanyu', 22), ( 'guanyu', 25), ('zhangfei', 22), ('zhangfei', 25)], names=['name', 'number'])
# 需要展开成列表形式 strings = list("abc") lists = [1,2] m8 = pd.MultiIndex.from_product( [strings, lists], names=["alpha","number"]) m8
MultiIndex([('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)], names=['alpha', 'number'])
# 使用元组形式 strings = ("a","b","c") lists = [1,2] m9 = pd.MultiIndex.from_product( [strings, lists], names=["alpha","number"]) m9
MultiIndex([('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)], names=['alpha', 'number'])
# 使用range函数 strings = ("a","b","c") # 3个元素 lists = range(3) # 0,1,2 3个元素 m10 = pd.MultiIndex.from_product( [strings, lists], names=["alpha","number"]) m10
MultiIndex([('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ('b', 2), ('c', 0), ('c', 1), ('c', 2)], names=['alpha', 'number'])
# 使用range函数 strings = ("a","b","c") list1 = range(3) # 0,1,2 list2 = ["x","y"] m11 = pd.MultiIndex.from_product( [strings, list1, list2], names=["name","l1","l2"] ) m11 # 总个数 3*3*2=18
MultiIndex([('a', 0, 'x'), ('a', 0, 'y'), ('a', 1, 'x'), ('a', 1, 'y'), ('a', 2, 'x'), ('a', 2, 'y'), ('b', 0, 'x'), ('b', 0, 'y'), ('b', 1, 'x'), ('b', 1, 'y'), ('b', 2, 'x'), ('b', 2, 'y'), ('c', 0, 'x'), ('c', 0, 'y'), ('c', 1, 'x'), ('c', 1, 'y'), ('c', 2, 'x'), ('c', 2, 'y')], names=['name', 'l1', 'l2'])
df = pd.DataFrame({"name":["xiaoming","guanyu","zhaoyun"], "age":[23,39,34], "sex":["male","male","female"]}) df
pd.MultiIndex.from_frame(df)
MultiIndex([('xiaoming', 23, 'male'), ( 'guanyu', 39, 'male'), ( 'zhaoyun', 34, 'female')], names=['name', 'age', 'sex'])
# 可以自定义名字 pd.MultiIndex.from_frame(df,names=["col1","col2","col3"])
MultiIndex([('xiaoming', 23, 'male'), ( 'guanyu', 39, 'male'), ( 'zhaoyun', 34, 'female')], names=['col1', 'col2', 'col3'])
df1 = pd.DataFrame({"col1":list("ababbc"), "col2":list("xxyyzz"), "number1":range(90,96), "number2":range(100,106)}) df1
df2 = df1.groupby(["col1","col2"]).agg({"number1":sum, "number2":np.mean}) df2
df2.index
MultiIndex([('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y'), ('b', 'z'), ('c', 'z')], names=['col1', 'col2'])
df3 = df1.pivot_table(values=["col1","col2"],index=["col1","col2"]) df3
df3.index
MultiIndex([('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y'), ('b', 'z'), ('c', 'z')], names=['col1', 'col2'])
以上是如何使用Python的pandas庫建立多層次索引(MultiIndex)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!