【问题标题】:How to create a Pandas dataframe with multiindex columns with several level 0?如何创建具有多个级别 0 的多索引列的 Pandas 数据框?
【发布时间】:2021-04-18 13:03:54
【问题描述】:

我想构建一个在列中有多个索引的数据框。必须有两个级别,如下例所示(0 和 1),但级别 0 route 分配给第 1 列和第 2 列,级别 0 action 分配给第 3 列。

我该怎么做?

在此示例中,我可以将级别 0 route 分配给第 1、2 和 3 列:

indexes = pd.MultiIndex.from_tuples([['paris']], names=['name'])
columns = pd.MultiIndex.from_product([['route'], ['type', 'action src', 'action dst']], names=['first', 'second'])
df = pd.DataFrame([[2, 3, 4]], index=indexes, columns=columns)
df

first   route
second  type    action src  action dst
name            
paris   2   3   4

但是想要的输出是这样的:

first   route   action
second  type    source  destination
name            
paris   2   3   4

我不确定这个问题的标题是否恰当,所以请随意给它一个更合适的标题。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用pandas.MultiIndex.from_arrays()

    import pandas as pd
    
    indexes = pd.MultiIndex.from_tuples([['paris']], names=['name'])
    columns = pd.MultiIndex.from_arrays([['route', 'action', 'action'], ['type', 'source', 'destination']], names=['first', 'second'])
    
    df = pd.DataFrame([[2, 3, 4]], index=indexes, columns=columns)
    
    print(df)
    
    first  route action            
    second  type source destination
    name                           
    paris      2      3           4
    

    【讨论】:

      【解决方案2】:

      只需使用pandas.MultiIndex.from_arrays():

      col = pd.MultiIndex.from_arrays([['route', 'action', 'action'], ['type', 'source', 'destination']], names=['first', 'second'])
      

      最后:

      df.columns=col
      

      现在,如果您打印 df,您将获得所需的输出:

      first   route   action
      second  type    source  destination
      name            
      paris   2           3       4
      

      【讨论】:

        猜你喜欢
        • 2014-08-09
        • 2020-02-22
        • 2020-12-17
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        相关资源
        最近更新 更多