You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将带MultiIndex的Pandas透视表转换为嵌套字典

Convert Pandas MultiIndex Pivot Table to Nested Dictionary

Hey there! I totally get the frustration of scouring for solutions that fit your exact use case—converting a Pandas MultiIndex pivot table into a nested dictionary for easy, intuitive access is a common need but not always straightforward. Let's break this down with practical examples and flexible methods.

Step 1: Example MultiIndex Pivot Table

First, let's create a sample pivot table with a MultiIndex to mirror the structure you're likely working with:

import pandas as pd

# Sample dataset
data = {
    'Category': ['Electronics', 'Electronics', 'Clothing', 'Clothing', 'Electronics'],
    'Subcategory': ['Phones', 'Laptops', 'Shirts', 'Pants', 'Phones'],
    'Brand': ['Apple', 'Dell', 'Nike', 'Levi\'s', 'Samsung'],
    'Monthly Sales': [1200, 900, 600, 750, 800]
}

df = pd.DataFrame(data)
# Create pivot table with 3-level MultiIndex: Category -> Subcategory -> Brand
pivot_table = df.pivot_table(index=['Category', 'Subcategory', 'Brand'], values='Monthly Sales')

Method 1: Recursive Function (Works for Any Number of Index Levels)

This is the most flexible approach—it handles MultiIndexes with 2, 3, or more levels automatically. The function recursively groups by each index level and builds out the nested structure:

def multiindex_to_nested(df):
    # Base case: if only one index level left, convert to dict
    if df.index.nlevels == 1:
        return df.to_dict('index')
    # Recursive case: group by the first index level, then process the rest
    nested = {}
    for top_level_key, subgroup in df.groupby(level=0):
        # Drop the top index level and recurse
        nested[top_level_key] = multiindex_to_nested(subgroup.droplevel(0))
    return nested

# Convert the pivot table
result_dict = multiindex_to_nested(pivot_table)

What the Output Looks Like

You’ll get a clean nested structure that lets you access data exactly how you’d expect:

# Access Samsung's phone sales
print(result_dict['Electronics']['Phones']['Samsung']['Monthly Sales'])
# Output: 800

Method 2: Simplified Approach for 2-Level MultiIndexes

If your pivot table only has two index levels, you can use Pandas built-in methods for a quicker solution:

# For 2-level indexes: unstack and convert to dict
two_level_dict = pivot_table['Monthly Sales'].unstack(level=0).to_dict('series')
# Or reverse the level order if needed
two_level_dict_reversed = pivot_table['Monthly Sales'].unstack(level=1).to_dict('series')

Key Notes

  • The recursive method is future-proof: if you later add more index levels to your pivot table, you won’t need to modify the code.
  • If your pivot table has multiple value columns, the recursive method will include all of them in the innermost dictionaries, which is perfect for accessing multiple metrics at once.

内容的提问来源于stack exchange,提问作者Jabb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:23:42