【问题标题】:Converting ordered dictionary into new columns in Python Pandas在 Python Pandas 中将有序字典转换为新列
【发布时间】:2020-02-11 10:37:48
【问题描述】:

在我的数据框中,某些列采用 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,为了简单起见,我只包含了数据集中的一列,即发明者

【问题讨论】:

  • df = pd.DataFrame(inventors[0])?您没有说 @ 去哪里,并且您没有包含本身是嵌套字典的列
  • 让我编辑问题

标签: python pandas ordereddictionary


【解决方案1】:

你考虑过 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2022-09-30
    • 1970-01-01
    • 2014-01-05
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多