我有一个 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 |
这是一种非常奇怪的格式,但这就是 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 | | |
我该怎么做?
最佳答案
最好的方法是将 read_excel
中的列转换为 MultiIndex
通过参数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)
关于python - 从具有重复列的 2 行创建多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432119/