【发布时间】:2022-11-17 22:11:30
【问题描述】:
我一直在努力摆脱嵌套的深度字典丁到熊猫数据框。
我已经尝试使用递归函数,如下所示,但我的问题是,当我迭代 KEY 时,我不知道之前的密钥是什么。
我也尝试过使用 json.normalize,来自 dict 的 pandas,但我总是在列中以点结束......
示例代码:
def iterate_dict(d, i = 2, cols = []):
for k, v in d.items():
# missing here how to check for the previous key
# so that I can create an structure to create the dataframe.
if type(v) is dict:
print('this is k: ', k)
if i % 2 == 0:
cols.append(k)
i+=1
iterate_dict(v, i, cols)
else:
print('this is k2: ' , k, ': ', v)
iterate_dict(test2)
这是我的字典的一个例子:
# example 2
test = {
'column-gender': {
'male': {
'column-country' : {
'FRENCH': {
'column-class': [0,1]
},
('SPAIN','ITALY') : {
'column-married' : {
'YES': {
'column-class' : [0,1]
},
'NO' : {
'column-class' : 2
}
}
}
}
},
'female': {
'column-country' : {
('FRENCH', 'SPAIN') : {
'column-class' : [[1,2],'#']
},
'REST-OF-VALUES': {
'column-married' : '*'
}
}
}
}
}
这就是我希望数据框的样子:
欢迎任何建议:)
【问题讨论】:
标签: python json pandas dictionary nested