从两行重复的列创建多索引

时间:2018-11-22 13:31:34

标签: python pandas

我有一个用熊猫读取的excel文件,并转换为数据框。这是数据框的示例:

|               | 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            |

这是一种非常奇怪的格式,但这就是excel文件中的内容。首先,前2行甚至不是多索引形式。

我设法通过下面的代码将其放入多索引,但是有些列是重复的(例如,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 个答案:

答案 0 :(得分:0)

最好是通过参数MultiIndex将列转换为read_excel中的header=[0,1]

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

然后将swaplevelsort_index结合使用:

df = df.swaplevel(0,1, axis=1).sort_index(axis=1, level=0)
相关问题