您的位置: 网站首页> Pandas教程> 当前文章

from_arrays、from_tuples、from_product、from_frame创建多重索引

老董2022-08-14155围观,100赞

  推荐7种方式实现pandas创建多重索引。上篇文章我们给pandas创建多重索引是直接给index或者columns参数传递原生二维列表,实际上才pandas中有一些比较常用的方法来创建多重索引,分别介绍如下。

  1、from_arrays

# ‐*‐ coding: utf‐8 ‐*‐
import pandas as pd

arrays = [['bj', 'bj','sh','sh'], ['one', 'one','two','two']]
index = pd.MultiIndex.from_arrays(arrays, names=('city', 'num'))
df = pd.DataFrame([[11,11],[22,22],[33,33],[44,44]],index=index)
print(df)
           0   1
city num        
bj   one  11  11
     one  22  22
sh   two  33  33
     two  44  44

  2、from_tuples

# ‐*‐ coding: utf‐8 ‐*‐
import pandas as pd

arrays = [
    ["bj", "bj", "sh", "sh",],
    ["one", "two", "one", "two",],
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["city", "num"])

df = pd.DataFrame([[11,11],[22,22],[33,33],[44,44]],index=index)
print(df)
print('==============')
df = pd.DataFrame([[11,11,11,11],[22,22,22,22]],columns=index)
print(df)
           0   1
city num        
bj   one  11  11
     two  22  22
sh   one  33  33
     two  44  44
==============
city  bj      sh    
num  one two one two
0     11  11  11  11
1     22  22  22  22

  3、from_product

# ‐*‐ coding: utf‐8 ‐*‐
import pandas as pd

iterables = [["bj", "sh",], ["one", "two"]]
index = pd.MultiIndex.from_product(iterables, names=["city", "num"])

df = pd.DataFrame([[11,11],[22,22],[33,33],[44,44]],index=index)
print(df)
print('==============')
df = pd.DataFrame([[11,11,11,11],[22,22,22,22]],columns=index)
print(df)
           0   1
city num        
bj   one  11  11
     two  22  22
sh   one  33  33
     two  44  44
==============
city  bj      sh    
num  one two one two
0     11  11  11  11
1     22  22  22  22

  4、from_frame创建多重索引

  这个函数传入一个 df,返回这个df的数据值(注意不是df的索引),该数据可作为多重索引去创建新的df

# ‐*‐ coding: utf‐8 ‐*‐
import pandas as pd

iterables = [["bj", "sh",], ["one", "two"]]
index = pd.MultiIndex.from_product(iterables, names=["city", "num"])

df = pd.DataFrame([[11,11],[22,22],[33,33],[44,44]],index=index)

index = pd.MultiIndex.from_frame(df)
print(index)
print('-----------------')
df = pd.DataFrame([['a','a'],['b','b'],['c','c'],['d','d']],index=index)
print(df)
MultiIndex([(11, 11),
            (22, 22),
            (33, 33),
            (44, 44)],
           names=[0, 1])
-----------------
       0  1
0  1       
11 11  a  a
22 22  b  b
33 33  c  c
44 44  d  d

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    from_arrays、from_tuples、from_product、from_frame创建多重索引文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200