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

如何将单行Pandas多层索引DataFrame转为索引名-值字典?

Convert Single-Row MultiIndex DataFrame to Target Dictionary

Got it, let's solve this quickly! Since your filtered Pandas DataFrame always has exactly one row with a MultiIndex (index1, index2, index3) and you don't need the Value column, here are two simple, reliable ways to get the dictionary format you want:

Method 1: Direct Index Tuple Pairing

This is the most concise approach—we'll just pair the index names with the values from the single row's index:

# Assume your DataFrame is named df
target_dict = dict(zip(df.index.names, df.index[0]))

How it works:

  • df.index.names returns the list of your MultiIndex labels: ['index1', 'index2', 'index3']
  • df.index[0] grabs the index values of the only row as a tuple: (1, 5, 3)
  • zip() matches each index name with its corresponding value, and dict() converts that pairings into your desired dictionary.

Method 2: Convert Index to DataFrame First

If you prefer a more explicit approach, you can turn the MultiIndex into a regular DataFrame and then convert it to a dictionary:

target_dict = df.index.to_frame(index=False).to_dict('records')[0]

How it works:

  • df.index.to_frame() converts the MultiIndex into a DataFrame where each index level becomes a column
  • index=False removes the redundant default index from this new DataFrame
  • .to_dict('records') returns a list containing one dictionary (since there's only one row), and we grab the first element to get your target dict.

Either method will give you exactly {'index1': 1, 'index2': 5, 'index3': 3}—pick whichever fits your coding style better!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:21:13