如果我理解正确,根据您在主贴评论中的定义,我已经找到了一种可以完成任务的方法。
首先,根据您的说法,数据将如下所示:
data = {'text' : ['Barack Obama was president of the United States in 2008.'],
'annotation' : ['MWE_type 0 12 MWE_type 34 47']}
我们将维护一个
final_list
,它基本上是一个列表的列表,其中每个内部列表将是每行的输出。
我们可以通过
df.iterrows()
迭代每一行,并从
row['text']
和使用
row['annotation']
来提取每一行的结果。
for index, row in df.iterrows():
我们可以通过正则表达式来提取索引对:
re.findall(r'\d+ \d+', row['annotation'])
我们可以遍历这个索引对列表,并将相应的子字符串附加到基于行的结果列表中。
for indexes in index_list:
start, end = map(int, indexes.split())
result.append(row['text'][start:end])
在迭代行结束时,我们可以将基于该行的结果列表附加到
final_list
中:
final_list.append(result)
最后,将
final_list
分配给
df['result']
:
df['result'] = final_list
整个程序如下所示:
import pandas as pd
import re
data = {'text' : ['Barack Obama was president of the United States in 2008.'],
'annotation' : ['MWE_type 0 12 MWE_type 34 47']}
df = pd.DataFrame(data)
final_list = []
for index, row in df.iterrows():
result = []
index_list = re.findall(r'\d+ \d+', row['annotation'])
for indexes in index_list:
start, end = map(int, indexes.split())
result.append(row['text'][start:end])
final_list.append(result)
df['result'] = final_list
print(df)
你将得到:
text ... result
0 Barack Obama was president of the United State... ... [Barack Obama, United States]
{'text' : ['Barack Obama was president of the United States in 2008.'], 'annotation' : [['MWE_type 0 12','MWE_type 34 47']]}
而且annotation
列的每一行都可以是一个字符串列表,对吧? - devRedditMWE_type 0 12
或MWE_type 34 47
,而不是两者都获取,对吗? - devReddit