【问题标题】:Python Multilevel Indexing using pandas read_csv method使用 pandas read_csv 方法的 Python 多级索引
【发布时间】:2019-02-04 05:53:12
【问题描述】:

我想将下表作为 pandas 数据框阅读

说dataframe是df,目的是查询 df['acct_id']['A']['0-3_mon] 应该给我 10

我已经为面板数据完成了它,其中所有内容都是一列,然后您为横截面和时间序列创建多级索引。

但是在这里,源数据本身有两个以上的列。如何将此 csv 作为多级索引读取?我被困在这里,任何想法。

如果您想查看一些类似的工作 - https://lectures.quantecon.org/py/pandas_panel.html

非常感谢。

【问题讨论】:

    标签: python pandas csv dataframe data-science


    【解决方案1】:

    MultiIndex创建DataFrame,因为deprecate panel

    df = pd.read_csv(file, header=[0,1], index_col=[0])
    

    然后通过slicers选择:

    idx = pd.IndexSlice
    print (df.loc[1, idx['A', '0-3_mon']])
    

    示例:没有多索引名称:

    import pandas as pd
    
    temp=u"""A;A;B;B
    0-3_mon;3-6_mon;0-3_mon;3-6_mon
    1;10;12;14;18
    2;11;15;17;19
    3;13;16;21;20"""
    #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(pd.compat.StringIO(temp), sep=";", header=[0,1])
    print (df)
            A               B        
      0-3_mon 3-6_mon 0-3_mon 3-6_mon
    1      10      12      14      18
    2      11      15      17      19
    3      13      16      21      20
    
    print (df.columns)
    MultiIndex(levels=[['A', 'B'], ['0-3_mon', '3-6_mon']],
               labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
    
    idx = pd.IndexSlice
    print (df.loc[1, idx['A', '0-3_mon']])
    10
    

    Sample 具有指定的 MultiIndex 名称:

    import pandas as pd
    
    temp=u"""acct_id;A;A;B;B
    level;0-3_mon;3-6_mon;0-3_mon;3-6_mon
    1;10;12;14;18
    2;11;15;17;19
    3;13;16;21;20"""
    #after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
    df = pd.read_csv(pd.compat.StringIO(temp), sep=";", index_col=[0], header=[0,1])
    print (df)
    acct_id       A               B        
    level   0-3_mon 3-6_mon 0-3_mon 3-6_mon
    1            10      12      14      18
    2            11      15      17      19
    3            13      16      21      20
    
    print (df.columns)
    
    MultiIndex(levels=[['A', 'B'], ['0-3_mon', '3-6_mon']],
               labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
               names=['acct_id', 'level'])
    
    idx = pd.IndexSlice
    print (df.loc[1, idx['A', '0-3_mon']])
    10
    

    【讨论】:

    • 谢谢,它是如此迅速,正是我想要的。非常感谢朋友。
    猜你喜欢
    • 1970-01-01
    • 2018-01-13
    • 2012-09-11
    • 2019-03-17
    • 1970-01-01
    • 2021-12-31
    • 2018-06-10
    • 2019-12-26
    • 2019-11-09
    相关资源
    最近更新 更多