Home >Backend Development >Python Tutorial >How to Flatten a Hierarchical Column Index in a Pandas DataFrame?

How to Flatten a Hierarchical Column Index in a Pandas DataFrame?

DDD
DDDOriginal
2024-12-14 19:24:16536browse

How to Flatten a Hierarchical Column Index in a Pandas DataFrame?

How to Flatten a Hierarchical Index in Columns

Problem:

You have a DataFrame with a hierarchical index in columns and want to flatten it into a single level.

Answer:

The most straightforward approach is to set the columns to the top level of the hierarchy using the following code:

df.columns = df.columns.get_level_values(0)

Alternative Approach:

If you want to combine the MultiIndex entries into a single Index, you can use the following code for columns with string entries:

df.columns = [' '.join(col).strip() for col in df.columns.values]

Explanation:

This code loops over the MultiIndex entries, joining the entries in each level with a space and then removing any leading or trailing whitespace. The resulting list of strings is assigned to the DataFrame's columns, creating a flattened index.

The above is the detailed content of How to Flatten a Hierarchical Column Index in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn