df.to_dict 将重复索引 (pandas) 作为嵌套字典中的主键

df.to_dict make duplicated index (pandas) as primary key in a nested dict

我有这个数据框,我想将其转换为 python 中的字典,我还有许多其他类别,但为简单起见只显示了两个

Category   Name                     Description             Price       
Diesel     Land Rover               No Description found    £ x
Electric   Tesla Model X            No Description found    £ x

我想要这样的输出

dict = {"Category": {"Diesel" : {
                                "Name": "Land Rover", 
                                "Description":"No Description Found", 
                                "Price": "£ x" },
                                           
                    "Electric" : {"Name": "Tesla Model X", 
                                  "Description":"No Description Found", 
                                  "Price": "£ x" }
                    }               
        }

您可以先为每条记录创建字典,然后按类别分组以创建所需的最终字典格式。

df['dict'] = df[['Name', 'Description', 'Price']].to_dict("records")

dictionary = dict()
dictionary['Category'] = df.groupby('Category')['dict'].apply(list).to_dict()

您可以在不分配额外的列或使用 list:

聚合的情况下执行此操作
def collect(category):
  return category[['Name', 'Description', 'Price']].to_dict('records')

data = {'Category': df.groupby('Category').apply(collect).to_dict()}

为了便于阅读,我创建了一个单独的函数 - 当然,您也可以将它作为 lambda 传递:

{
  'Category': df.groupby('Category').apply(
    lambda x: x[['Name', 'Description', 'Price']].to_dict('records')).to_dict()
}