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

标签 python pandas

我有一个 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])

然后使用 swaplevelsort_index :

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

关于python - 从具有重复列的 2 行创建多重索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53432119/

相关文章:

python - 为什么我无法测试 Django REST Frameworks AuthToken?

python - java.io.IOException : Cannot run program "python" using Spark in Pycharm (Windows) 异常

python - 透视 Pandas Dataframe,没有数字类型,索引不是唯一的

具有 3 级多索引的 Pandas 数据透视表

python - 具有从配置文件中读取 configparser 的单元测试 python 代码

python - Python UnitTest 中的 assertEqual 应该做什么?

python - 将消息存储到文本文件 Discord.py

矩阵的 Python Scipy spearman 相关性与双数组相关性不匹配,也不匹配 pandas.Data.Frame.corr()

python - 如何添加每列均值的额外卷?

python - 识别 Pandas 数据框中并发事件的简单方法