【问题标题】:Creating Multi-level pandas dataframe创建多级熊猫数据框
【发布时间】:2022-01-13 08:02:11
【问题描述】:

我正在尝试基于我拥有的数据框创建分层数据框。我设法创建了一个多索引数据框,如下所示:

Image of dataframe structure

所以我的数据框索引如下:

MultiIndex([('x',    'yellow'),
            ('x',      'blue'),
            ('x',     'green'),
            ('x',     'white'),
            ('x',     'ind10'),
            ('x',       'red'),
            ('x', 'turquoise'),
            ('x',     'black'),
            ('x',    'purple'),
            ('x',    'orange'),
            ('x',     'ind11'),
            ('y',    'yellow'),
            ('y',      'blue'),
            ('y',     'green'),
            ('y',     'white'),
            ('y',     'ind10'),
            ('y',       'red'),
            ('y', 'turquoise'),
            ('y',     'black'),
            ('y',    'purple'),
            ('y',    'orange'),
            ('y',     'ind11')],
           )

现在我正在尝试将其转换为具有以下结构的东西:

yellow  x   ........
        y   ........
orange  x   ........
        y   ........
.
.
.
ind11   x   ........
        y   ........

但我似乎无法做到这一点。我尝试了各种形式的pd.MultiIndex.from_frame,但无济于事。

任何帮助将不胜感激

【问题讨论】:

    标签: python pandas multi-index hierarchical-data


    【解决方案1】:

    IIUC 使用MultiIndex.to_frame:

    df1 = mux.to_frame(index=False)
    
    df1 = df.columns.to_frame(index=False)
    

    或许:

    df2 = df.T
    

    【讨论】:

      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 2016-01-13
      • 2022-07-28
      • 1970-01-01
      • 2012-05-19
      • 2023-01-14
      相关资源
      最近更新 更多