• 08-pandas嵌套索引


    import numpy as np
    import pandas as pd
    #1.风格1
    df=pd.DataFrame(np.random.rand(4,2),
                    columns=["A","B"],
                    index=[["1","1","2","2"],
                           ["a","b","a","b"]])
    print(df)
    #2.风格2
    mindex=pd.MultiIndex.from_arrays([["a","a","b","b"],[1,2,1,2]])#双层索引对象
    df2=pd.DataFrame(np.random.rand(4,2),
                     columns=(["A","B"]),
                     index=mindex)
    print(df2)
    #3.风格3
    mindex=pd.MultiIndex.from_tuples([("a",1),("a",2),("b",1),("b",2)])#根据元组构建
    df3=pd.DataFrame(np.random.rand(4,2),
                     columns=(["A","B"]),
                     index=mindex)
    print(df3)
    #4.风格4
    mindex=pd.MultiIndex.from_product([["a","b"],[1,2]])#根据元组构建
    df4=pd.DataFrame(np.random.rand(4,2),
                     columns=(["A","B"]),
                     index=mindex)
    print(df4)
    #5.风格5
    mindex=pd.MultiIndex(levels=[["a","b"],[1,2]],
                         codes=[[0,0,1,1],[0,1,0,1]])#a对应00,b对应11
    df4=pd.DataFrame(np.random.rand(4,2),
                     columns=(["A","B"]),
                     index=mindex)
    print(df4)
    #6.
    index=[("beijing",2007),("beijing", 2017),
           ("beijing", 2027),("shenzhen",2007),
           ("shenzhen",2017),("shenzhen",2027)]
    money=np.random.rand(6)
    Mindex=pd.MultiIndex.from_tuples(index)
    city=pd.DataFrame(money,index=Mindex)
    print(city)
    

      

  • 相关阅读:
    自考新教材-p145_5
    自考新教材-p144_4
    自考新教材-p144_3
    自考新教材-p143_2
    自考新教材-p142_3(1)
    【SQL server】安装和配置
    【,net】发布网站问题
    【LR】关于宽带与比特之间的关系
    【LR】录制测试脚本中的基本菜单
    【LR】安装LR11后遇到的问题
  • 原文地址:https://www.cnblogs.com/wcyMiracle/p/12442957.html
Copyright © 2020-2023  润新知