繁体   English   中英

从 dataframe 创建嵌套字典,其中第一列将是父字典的键

[英]Create a nested dictionary from a dataframe where the first column would be the key for the parent dictionary

我正在尝试从 pandas DataFrame 创建一个嵌套字典。 该表的结构如下,是一个查找表,我想从中创建一个嵌套字典以供以后使用。

一个 C
苹果 1 快乐的
苹果 2 伤心
苹果 3 不是
1 新的
2 老的
1
2
3 老的

字典的格式需要如下,因为这将允许我用它来用它们的实际含义替换另一个数据框中的键值。 其中 apple、pear、liver 是列名,数字是使用的代码,而不是实际值,例如快乐的

d = {'apple':{1: 'happy', 2:'sad', 3:'not'}, 'pear':{1: 'new', 2: 'old'}, 'liver':{1: 'run', 2:'fire', 3:'old'}}

A列上使用 Pandas groupby ,然后遍历组以创建字典。 使用结合内置 function zip的字典理解,分别使用列BC作为键和值。

import pandas as pd

df = pd.read_csv('sample.csv', sep='\s+')
print(df)

g = df.groupby('A')

d = {}
for n,dfg in g:
    d[n] = {k:v for k,v in zip(dfg['B'],dfg['C'])}

print(d)

Output 来自d

{'apple': {1: 'happy', 2: 'sad', 3: 'not'}, 'liver': {1: 'run', 2: 'fire', 3: 'old'}, 'pear': {1: 'new', 2: 'old'}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM