首页 > 解决方案 > 来自 Pandas Dataframe 的 Spacy 训练数据

问题描述

我是 Python 新手,目前正在努力将数据框转换为以下格式。

例如,我有以下数据框(df1):

   fulltext                                   text       start    end     text1     start1  end1
0   Android Pay expands to Canada             Canada      23      29      0         0       0
1   Google Maps launches location sharing     Google       0      6       location  21      29

我试图从这个数据框达到的输出:

[
    ("Android Pay expands to Canada", {"entities": [(23, 29, "entity")]}),
    ("Google Maps launches location sharing", {"entities": [(0, 6, "entity"), (21, 29, "entity")]}),
]

我试过:1)

List =  []
for index, rows in df1.iterrows():
    my_list = [rows.start, rows.end]
    List.append(my_list)
    my_list.append('entity')
print(List)

并得到以下输出:

[[23, 29, 'entity'], [0, 6, 'entity']]

2)转换成元组:

List_tuple = [tuple(l) for l in List]

输出:

[(23, 29, 'entity'), (0, 6, 'entity')]

但这只是“start”和“end”列((21, 29, “entity”) 缺失,因为它是 start1 和 end 1)。您能否建议我如何继续为 n 行(我有大量行)制作这种列表,以防“start1”、“end1”、“start2”、“ end2" 等 - 将它们放在列表中(在字典内),如此处所示?

[
    ("Android Pay expands to Canada", {"entities": [(23, 29, "entity")]}),
    ("Google Maps launches location sharing", {"entities": [(0, 6, "entity"), (21, 29, "entity")]}),
]

非常感谢您的任何建议!我一直在努力解决它,我被卡住了,不知道如何继续......

标签: pythonpandas

解决方案


df.apply(lambda x: (x['fulltext'],{'entities':[(x['start'],x['end'],'entity')]}),axis=1).tolist()

希望这可以解决您的问题。


推荐阅读