![](/img/trans.png)
[英]create a nested dictionary from dataframe, where first column is the key for parent dictionary
[英]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
的字典理解,分别使用列B
和C
作为键和值。
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.