如何从Pandas DataFrame生成无额外层级的嵌套字典
解决方案
你可以在apply的匿名函数中,将设置完索引的DataFrame先提取description列,再执行to_dict操作,修改后的代码如下:
df.groupby("field_name")[["values","description"]].apply(lambda x: x.set_index("values")["description"].to_dict()).to_dict()
原代码问题说明
你之前的写法调用to_dict(orient="dict")时,会把所有列名作为字典的第一层级key,因此多出来了description嵌套层。直接提取单列后再转字典,就可以跳过列名这一层级,直接生成values到description的映射字典。
运行上述代码即可得到预期输出:
{'bar': {'key1': 'value4', 'key5': 'value6'}, 'foo': {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}}
内容的提问来源于stack exchange,提问作者lakeside
相关产品推荐
相关产品推荐

