【问题标题】:pandas set index with multilevel columns具有多级列的熊猫设置索引
【发布时间】:2019-06-27 18:53:23
【问题描述】:

考虑以下pd.DataFrame

df_index = pd.MultiIndex.from_product([['foo','bar'],['one','two','three']])
df = pd.DataFrame(np.random.randint(0,10,size=18, dtype='int').reshape((-1,6)), columns=df_index)

print(df)
                     foo                    bar
     one    two     three   one     two     three
   0    7   3         8       3     6         0
   1    2   5         9       4     3         6
   2    4   2         6       6     4         5

我希望将'foo' 和其中的所有子索引设置为索引。我怎样才能做到这一点?我正在努力解决'set_index'pd.IndexSlice,但仍然无法找到解决方案

【问题讨论】:

    标签: python pandas numpy multi-index


    【解决方案1】:

    您需要将MultiIndex 的所有级别作为元组传递。所以正确的格式应该是:

    df.set_index([('foo', 'one'), ('foo', 'two'), ('foo', 'three')])
    

    如果这很麻烦,您可以使用以下列表理解创建索引:

    idx = [x for x in df.columns if x[0] == 'foo']
    print(idx)
    #  [('foo', 'one'), ('foo', 'two'), ('foo', 'three')]
    
    df.set_index(idx)
    

    [出]

                                       bar          
                                       one two three
    (foo, one) (foo, two) (foo, three)              
    1          3          4              4   8     3
    5          1          0              4   7     5
    0          0          3              9   1     6
    

    【讨论】:

    • 我试过 df.set_index(('foo','one','two','three')) 和 df.set_index(('foo',('one','two' ,'three')))..那个偏题没用。
    猜你喜欢
    • 2021-10-10
    • 2017-05-03
    • 2021-11-28
    • 2020-04-27
    • 2021-05-14
    • 1970-01-01
    • 2020-12-02
    • 2019-05-03
    • 2020-12-05
    相关资源
    最近更新 更多