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
Release: 2024-12-14 19:24:16
Original
540 people have browsed it

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)
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template