【问题标题】:Splitting dictionary embedded into a list value column in a dataframe pandas拆分嵌入到数据框熊猫列表值列中的字典
【发布时间】:2020-10-20 15:57:30
【问题描述】:

我在数据框 df 中有一个列 authors,其中值首先在字典中,然后将字典添加到列表中。然后将列表存储在列中。如:

[{'family': 'Yaisy',
  'given': 'Lisa',
  'affiliation': [{'name': 'Department of Sciences, Faculty Sciences, University of Science'}]},
 {'family': 'Kite',
  'given': 'Hume',
  'affiliation': [{'name': 'Department of Sciences, Science and Technology'}]},
 {'family': 'Jones',
  'given name': 'Mike',
  'localId': 'aza',
  'affiliation': [{'name': 'Department of Health, Science and Technology'}]},
 {'family': 'abc',
  'given name': 'xyz',
  'affiliation': [{'name': 'Health Sciences, University of Science'}]}]

我想将此列表分成不同的列,其中键作为列名,值作为列值。由于键有重复的名称,我可以为每个列名添加 1,2,3 作为后缀。我尝试了this question中建议的解决方案

df.join(pd.json_normalize(df.authors))

但是,我首先需要将列表更改为一个简单的字典,然后使用上面的解决方案。所以我尝试展平列表以获取字典并将它们存储在同一列中:

df.author = [y for x in df.author for y in x]

但是在这里我得到了值的长度与索引的长度不匹配的错误。

谁能帮我解决这个问题?谢谢!

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    一种方法是手动构建记录列表并创建数据框:

    lst = [{'family': 'Yaisy',
      'given': 'Lisa',
      'affiliation': [{'name': 'Department of Sciences, Faculty Sciences, University of Science'}]},
     {'family': 'Kite',
      'given': 'Hume',
      'affiliation': [{'name': 'Department of Sciences, Science and Technology'}]},
     {'family': 'Jones',
      'given name': 'Mike',
      'localId': 'aza',
      'affiliation': [{'name': 'Department of Health, Science and Technology'}]},
     {'family': 'abc',
      'given name': 'xyz',
      'affiliation': [{'name': 'Health Sciences, University of Science'}]}]
    
    records = []
    for item in lst:
        records.append({
            'family': item['family'],
            'given': item.get('given', item.get('given name')),
            **item['affiliation'][0]
        })
    
    df = pd.DataFrame(records)
    print(df)
    

    打印:

      family given                                               name
    0  Yaisy  Lisa  Department of Sciences, Faculty Sciences, Univ...
    1   Kite  Hume     Department of Sciences, Science and Technology
    2  Jones  Mike       Department of Health, Science and Technology
    3    abc   xyz             Health Sciences, University of Science
    

    【讨论】:

    • 这个字典和列表是我数据框中一个单元格的一个例子。但是我的 df 中有一个完整的列,其中每个单元格都有这些字典和列表。因此,我需要一个可以应用于整个列的解决方案,也许是逐个单元格。
    • @Hanif 然后你可以用for item in df["my_column"]: 代替for item in lst:
    • 如果我尝试,我得到错误:TypeError: list indices must be integers or slices, not str
    • @Hanif 这意味着您的专栏中有一些其他结构。不看真实数据很难弄清楚...
    • 不幸的是,我无法共享所有数据框,因为其中包含个人数据,并且有超过 7000 行。这就是为什么需要一个解决方案,我不必手动构建具有特定列/键的数据框。
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2021-02-26
    • 2017-06-16
    • 2019-03-08
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多