python - 在 Python Pandas 中将有序字典转换为新列
问题描述
在我的数据框中,某些列采用 OrderedDictionary 格式。我如何将它们转换为新列(不知道哪些列包含 OrderedDictionary 和 OrderedDictionary 中的元素)
示例列:
inventors
[OrderedDict([('@sequence', '001'), ('@app-type', 'applicant'), ('@designation', 'us-only'), ('addressbook', OrderedDict([('last-name', 'Nahm'), ('first-name', 'Seung Hoon'), ('address', OrderedDict([('city', 'Daejeon'), ('country', 'KR')]))])), ('residence', OrderedDict([('country', 'KR')]))]), OrderedDict([('@sequence', '002'), ('@app-type', 'applicant'), ('@designation', 'us-only'), ('addressbook', OrderedDict([('last-name', 'Jang'), ('first-name', 'Hoon Sik'), ('address', OrderedDict([('city', 'Daegu'), ('country', 'KR')]))])), ('residence', OrderedDict([('country', 'KR')]))])]
我想将其转换为以下数据框(未写入所有列):
@sequence1 @app_type1 @designation1 @last_name1 @first_name1 ....
001 applicant us_only Nahm Seung Hoon
在此示例中,last_name 和 first_name 来自另一个嵌套字典。在数据中,我不知道哪些列包含 OrderedDictonary,为了简单起见,我只包含了数据集中的一列,它是发明者
解决方案
您是否考虑过 pandas from_dict()函数?
# Create example dict
import collections
inventors = collections.OrderedDict()
inventors['@sequence'] = "001"
inventors['@app-type'] = "applicant"
inventors['@designation'] = "us-only"
inventors['last-name'] = "Nahm"
inventors['first-name'] = "Seung Hoon"
# Import pandas to use from_dict function
import pandas as pd
# Use from_dict() function; include orient='index' for now to avoid index error
df = pd.DataFrame.from_dict(inventors, orient='index')
# Transpose for final output
df.T
推荐阅读
- cryptography - web2py 无法导入 pymysql 0.9.2:没有名为 cryptography.hazmat.backends 的模块
- javascript - 扩展网站 UI 以显示第三方内容
- kubernetes - coredns 无法正确解析服务名称
- javascript - 如何将字符串与多个变量匹配?
- javascript - 将 Angular 6 更新为 Angular 7 出错
- spring - @Transactional 不起作用,而 DefaultTransactionDefinition 起作用
- matplotlib - matplotlib 可以在 python3 中显示,但不能在 pyhon2 中显示
- spss - 在文件中保存变量列表
- javascript - 更新jQuery范围滑块的值
- reactjs - 有人可以破解 React Native 或任何传统 JS Native 应用程序的 API 调用吗