【问题标题】:Get an item value from a nested dictionary inside the rows of a pandas df and get rid off the rest从 pandas df 行内的嵌套字典中获取项目值并摆脱其余部分
【发布时间】:2021-04-20 07:17:12
【问题描述】:

我实现了allennlp's OIE,它提取嵌入在嵌套字符串中的主语、谓语、宾语信息(以 ARG0、V、ARG1 等的形式)。但是,我需要确保每个输出都链接到原句的给定ID

我生成了以下 pandas 数据帧,其中 OIE output 包含 allennlp 算法的原始输出。

当前输出:

sentence ID OIE output
'The girl went to the cinema' 'abcd' {'verbs':[{'verb': 'went', 'description':'[ARG0: The girl] [V: went] [ARG1:to the cinema]'}]}
'He is right and he is an engineer' 'efgh' {'verbs':[{'verb': 'is', 'description':'[ARG0: He] [V: is] [ARG1:right]'}, {'verb': 'is', 'description':'[ARG0: He] [V: is] [ARG1:an engineer]'}]}

我获取上表的代码:

oie_l = []

for sent in sentences:
  oie_pred = predictor_oie.predict(sentence=sent) #allennlp oie predictor
  for d in oie_pred['verbs']: #get to the nested info
    d.pop('tags') #remove unnecessary info
  oie_l.append(oie_pred)

df['OIE out'] = oie_l #add new column to df

期望的输出:

sentence ID OIE Triples
'The girl went to the cinema' 'abcd' '[ARG0: The girl] [V: went] [ARG1:to the cinema]'
'He is right and he is an engineer' 'efgh' '[ARG0: He] [V: is] [ARG1:right]'
'He is right and he is an engineer' 'efgh' '[ARG0: He] [V: is] [ARG1:an engineer]'

方法思路:

为了获得 'OIE Triples' 的所需输出,我正在考虑将初始 'OIE output' 转换为字符串,然后使用正则表达式来提取 ARG。但是,我不确定这是否是最佳解决方案,因为“ARG”可能会有所不同。另一种方法是迭代到 description: 的嵌套值,以列表的形式替换当前 OIE 输出中的内容,然后执行 df.explode() 方法来扩展它,以便正确的句子和 id 列是在“爆炸”之后链接到三元组。

感谢任何建议。

【问题讨论】:

    标签: python pandas triples allennlp


    【解决方案1】:

    你的第二个想法应该可以解决问题:

    import ast
    df["OIE Triples"] = df["OIE output"].apply(ast.literal_eval)
    
    df["OIE Triples"] = df["OIE Triples"].apply(lambda val: [a_dict["description"]
                                                             for a_dict in val["verbs"]])
    df = df.explode("OIE Triples").drop(columns="OIE output")
    

    如果"OIE output" 值不是真正的dicts 而是strings,我们通过ast.literal_eval 将它们转换为dicts。 (所以如果他们是dicts,你可以跳过前两行)。

    然后我们得到一个系列的每个value 的列表,该列表由"verbs" 编辑的最外层dict 键的"description"s 组成。

    最后explode 这个description 列出了drop "OIE output" 列,因为它不再需要了。

    得到

                                  sentence      ID                                      OIE Triples
    0        'The girl went to the cinema'  'abcd'  [ARG0: The girl] [V: went] [ARG1:to the cinema]
    1  'He is right and he is an engineer'  'efgh'                  [ARG0: He] [V: is] [ARG1:right]
    1  'He is right and he is an engineer'  'efgh'            [ARG0: He] [V: is] [ARG1:an engineer]
    

    【讨论】:

    • 不知道 'ast' 方法。干杯!!我还找到了另一种解决它的方法,虽然更耗时,但它有效:将初始 df 转换为带有 'to_dict' 的字典;弹出不需要的嵌套项,并转换回新的 df。
    猜你喜欢
    • 2018-06-17
    • 2021-12-31
    • 2021-07-11
    • 2021-04-28
    • 2012-11-14
    • 2021-02-01
    • 2020-09-02
    • 1970-01-01
    • 2017-02-20
    相关资源
    最近更新 更多