python - 在数据框中转换嵌套字典?
问题描述
我一直在尝试解析数据框中的嵌套字典。我从 dict 制作了这个 df,但无法弄清楚这个嵌套的。
df
First second third
0 1 2 {nested dict}
嵌套字典:
{'fourth': '4', 'fifth': '5', 'sixth': '6'}, {'fourth': '7', 'fifth': '8', 'sixth': '9'}
我想要的输出是:
First second fourth fifth sixth fourth fifth sixth
0 1 2 4 5 6 7 8 9
编辑:原始字典
'archi': [{'fourth': '115',
'fifth': '-162',
'sixth': '112'},
{'fourth': '52',
'fifth': '42',
'sixth': ' 32'}]
解决方案
我不能退出告诉“第三”列中嵌套 dict 的格式,但这是我建议使用Python 的方法:Pandas dataframe from Series of dict作为起点。这是一个可重现的字典和数据框:
nst_dict = {'archi': [{'fourth': '115', 'fifth': '-162', 'sixth': '112'},
{'fourth': '52', 'fifth': '42','sixth': ' 32'}]}
df = pd.DataFrame.from_dict({'First':[1,2], 'Second':[2,3],
'third': [nst_dict,nst_dict]})
然后你需要首先访问字典中的列表,然后是列表中的项目:
df.thrd_1 = df.third.apply(lambda x: x['archi']) # convert to list
df.thrd_1a = df.thrd_1.apply(lambda x: x[0]) # access first item
df.thrd_1b = df.thrd_1.apply(lambda x: x[1]) # access second item
out = df.drop('third', axis=1).merge(
df.thrd_1a.apply(pd.Series).merge(df.thrd_1a.apply(pd.Series),
left_index=True, right_index=True),
left_index=True, right_index=True)
print(out)
First Second fourth_x fifth_x sixth_x fourth_y fifth_y sixth_y
0 1 2 115 -162 112 115 -162 112
1 2 3 115 -162 112 115 -162 112
我会尝试用它来清理它collections.abc
并变成一个函数,但这应该可以解决你的具体情况。
推荐阅读
- codeigniter - 无法在 Codeigniter 中调整照片大小
- python - 在python中对事务描述和计数进行分组
- struct - 在HashSet中插入struct时的借用问题
- php - 教义迁移令
- swift - 为什么我必须将 swift 协议中的协议和包含的可选功能都标记为@objc?
- python - 远程使用 Pywinrm 的 Python 3.6
- c++ - 如何使用 nlhoman json 在 C++ 中将相同的关键 json 数据合并为一个
- javascript - 获取在 LUIS 上添加的句子
- android - 使用 recyclerview 滚动 coordinatorLayout 中的 Android 抖动错误(instagram 也有此错误)
- c++ - 何时在 C++ 中的嵌套类上使用 Pimpl 模式,反之亦然?