【问题标题】:How to populate dataframe from dictionary in loop如何在循环中从字典中填充数据框
【发布时间】:2018-06-26 05:11:16
【问题描述】:

我正在尝试对文本执行实体分析,我想将结果放入数据框中。目前,结果既不存储在字典中,也不存储在 Dataframe 中。使用两个函数提取结果。

df:

ID    title    cur_working    pos_arg         neg_arg                             date
132   leave    yes            good coffee     management, leadership and salary   13-04-2018
145   love it  yes            nice colleagues long days                           14-04-2018

我有以下代码:

result = entity_analysis(df, 'neg_arg', 'ID')

#This code loops through the rows and calls the function entities_text()
def entity_analysis(df, col, idcol):
    temp_dict = {}
    for index, row in df.iterrows():
        id = (row[idcol])
        x = (row[col])
        entities = entities_text(x, id)
        #temp_dict.append(entities)
    #final = pd.DataFrame(columns = ['id', 'name', 'type', 'salience'])
    return print(entities)

def entities_text(text, id):
    """Detects entities in the text."""
    client = language.LanguageServiceClient()
    ent_df = {}
    if isinstance(text, six.binary_type):
        text = text.decode('utf-8')

    # Instantiates a plain text document.
    document = types.Document(
        content=text,
        type=enums.Document.Type.PLAIN_TEXT)

    # Detects entities in the document.
    entities = client.analyze_entities(document).entities

    # entity types from enums.Entity.Type
    entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',
                   'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')

    for entity in entities:
        ent_df[id] = ({
            'name': [entity.name],
            'type': [entity_type[entity.type]],
            'salience': [entity.salience]
        })
    return print(ent_df)

此代码给出以下结果:

{'132': {'name': ['management'], 'type': ['OTHER'], 'salience': [0.16079013049602509]}}
{'132': {'name': ['leadership'], 'type': ['OTHER'], 'salience': [0.05074194446206093]}}
{'132': {'name': ['salary'], 'type': ['OTHER'], 'salience': [0.27505040168762207]}}
{'145': {'name': ['days'], 'type': ['OTHER'], 'salience': [0.004272154998034239]}}

我在函数entity_analysis() 中创建了temp_dictfinal 数据框。 This thread 解释说,在循环中附加到数据帧效率不高。 我不知道如何以有效的方式填充数据框These threads 与我的问题有关,但它们解释了如何从现有数据中填充数据框。当我尝试使用 temp_dict.update(entities) 并返回 temp_dict 时出现错误:

在实体分析中 temp_dict.update(实体) TypeError: 'NoneType' 对象不可迭代

我希望输出是这样的:

ID          name                  type                salience
132         management            OTHER               0.16079013049602509 
132         leadership            OTHER               0.05074194446206093 
132         salary                OTHER               0.27505040168762207 
145         days                  OTHER               0.004272154998034239 

【问题讨论】:

  • 您是否刚刚将问题从“当前结果存储在字典中”更改为“当前结果存储在字典中“?这对你原来的问题有很大的改变,我认为应该回滚它是公平的,因为已经有了答案。

标签: python pandas dictionary google-natural-language


【解决方案1】:

一种解决方案是通过您的 entities 迭代创建列表列表。然后将您的列表输入pd.DataFrame

LoL = []

for entity in entities:
    LoL.append([id, entity.name, entity_type[entity.type], entity.salience])

df = pd.DataFrame(LoL, columns=['ID', 'name', 'type', 'salience'])

如果您需要当前生成格式的字典,那么您可以将当前逻辑添加到for 循环中。但是,首先检查您是否需要使用两个结构来存储相同的数据。

【讨论】:

  • 感谢您的回答,我找到了解决办法。我创建了多个字典,因为我必须遍历文本和单词。为混乱道歉。
猜你喜欢
  • 2022-01-11
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2012-11-06
相关资源
最近更新 更多