Home >Backend Development >Python Tutorial >How to Flatten a Hierarchical Column Index in a Pandas DataFrame?
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!