代码之家  ›  专栏  ›  技术社区  ›  JPFrancoia

从具有重复列的2行创建多索引

  •  1
  • JPFrancoia  · 技术社区  · 7 年前

    我有一个excel文件,我用pandas读取并转换为数据框。以下是数据帧的示例:

    |               | salads_count | salads_count | salads_count | carrot_counts | carrot_counts | carrot_counts |
    |---------------|--------------|--------------|--------------|---------------|---------------|---------------|
    |               | 01.2016      | 02.2016      | 03.2016      | 01.2016       | 02.2016       | 03.2016       |
    | farm_location |              |              |              |               |               |               |
    | sweden        | 42           | 41           | 43           | 52            | 51            | 53            |
    

    我用下面的代码设法将其放入一个多索引中,但有些列是重复的(例如,salads_count出现了几次):

    arrays = [df.columns.tolist(), df.iloc[0].tolist()]
    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples)
    df.columns = index
    

    |               | salads_count |         |         | carrot_counts |         |         |
    |---------------|--------------|---------|---------|---------------|---------|---------|
    |               | 01.2016      | 02.2016 | 03.2016 | 01.2016       | 02.2016 | 03.2016 |
    | farm_location |              |         |         |               |         |         |
    | sweden        | 42           | 41      | 43      | 52            | 51      | 53      |
    

    |               | 01.2016      |              | 02.2016      |             |   |   |
    |---------------|--------------|--------------|--------------|-------------|---|---|
    |               | carrot_count | salads_count | carrot_count | salad_count |   |   |
    | farm_location |              |              |              |             |   |   |
    | sweden        | 52           | 42           | 51           | 41          |   |   |
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   jezrael    7 年前

    最好的方法是将列转换为 MultiIndex read_excel 按参数 header=[0,1] :

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

    然后使用 swaplevel 具有 sort_index :

    df = df.swaplevel(0,1, axis=1).sort_index(axis=1, level=0)