如何将单行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.namesreturns 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, anddict()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 columnindex=Falseremoves 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
相关产品推荐
相关产品推荐

