• Pandas excel 双标题 多级索引 层次化索引 MultiIndex


    1 import pandas as pd
    2 import numpy as np

    多级索引

    多级索引(也称层次化索引)是pandas的重要功能,可以在Series、DataFrame对象上拥有2个以及2个以上的索引。 
    实质上,单级索引对应Index对象,多级索引对应MultiIndex对象。

    一、Series对象的多级索引

     

    • 多级索引Series对象的创建
    se1=pd.Series(np.random.randn(4),index=[list("aabb"),[1,2,1,2]])
    se1

    代码结果:

    a  1    0.945676
       2    1.240454
    b  1    1.021960
       2    0.363063
    dtype: float64
    
    • 子集的选取
    se1['a']
    

    代码结果:

    1    0.945676
    2    1.240454
    dtype: float64
    

      

    se1['a':'b']
    

    代码结果:

      

    a  1    0.945676
       2    1.240454
    b  1    1.021960
       2    0.363063
    dtype: float64

    甚至能内层选取

    se1[:,1]
    

    代码结果:

    a    0.945676
    b    1.021960
    dtype: float64
    

    二、DataFrame对象的多级索引

    • 创建
    df1=pd.DataFrame(np.arange(12).reshape(4,3),index=[list("AABB"),[1,2,1,2]],columns=[list("XXY"),[10,11,10]])
    df1
    

      

    代码结果:

        Y
        10  11 10
    A 1 0 1 2
    2 3 4 5
    B 1 6 7 8
    2 9 10 11


     
     

    每一层都可以赋名

    df1.columns.names=['XY','sum']
    df1.index.names=['AB','num']
    df1

    代码结果:

      XY Y
      sum  10 11 10
    AB num       
    A 1 0 1 2
    2 3 4 5
    B 1 6 7 8
    2 9 10 11


     
     

    · 可以创建MultiIndex对象再作为索引

    df1.index=pd.MultiIndex.from_arrays([list("AABB"),[3,4,3,4]],names=["AB","num"])
    df1
    

    代码结果:

      XY Y
      sum  10 11 10
    AB num       
    A 3 0 1 2
    4 3 4 5
    B 3 6 7 8
    4 9 10 11


     
     

    可以对各级索引进行互换

    df1.swaplevel('AB','num')
    

    代码结果:

      XY Y
      sum  10 11 10
    num  AB      
    3 A 0 1 2
    4 A 3 4 5
    3 B 6 7 8
    4 B 9 10 11


     
     

  • 相关阅读:
    Ubuntu18.04下使用pip3.8报错subprocess.CalledProcessError: Command ‘(‘lsb_release‘, ‘-a‘)‘ returned non-ze
    解决报错:ModuleNotFoundError: No module named ‘_sqlite3‘
    shell命令中find的用法
    Ubuntu 中卸载软件
    git使用
    django celery 使用
    Django 学习中遇到的问题
    1
    Mac 下安装brew(文末方法亲测有效)
    经典类与新式类的继承顺序
  • 原文地址:https://www.cnblogs.com/bianzhiwei/p/10431236.html
Copyright © 2020-2023  润新知