如何修改Python函数返回DataFrame中符合距离要求的词对位置列表?
修改函数以返回符合条件的词对位置列表
你完全可以直接在函数中返回符合条件的i和j组成的元组列表来实现需求,只需要对原函数做简单修改:
修改后的完整代码
import pandas as pd def identify_instances(string, word_1='can', word_2='help', allowed_distance=3): string_list = string.split(' ') indices_word_1 = [i for i, x in enumerate(string_list) if x == word_1] indices_word_2 = [i for i, x in enumerate(string_list) if x == word_2] # 将计数变量替换为列表,用于存储符合条件的位置对 result = [] for i in indices_word_1: for j in indices_word_2: _distance = abs(i - j) if _distance <= allowed_distance: # 符合条件时将位置对(i,j)添加到列表 result.append((i, j)) return result # 测试示例数据 data = [['ABC123', 'can you help me with this'], ['ABC456', 'I can not help with this, but they can help'], ['ABC789', 'No one can help can they']] pandasDF = pd.DataFrame(data, columns=['Record ID', 'String']) # 新增列存储位置对列表 pandasDF['can-NEAR-help Positions'] = pandasDF['String'].apply(identify_instances) # 输出目标结果 print(pandasDF[['Record ID', 'can-NEAR-help Positions']])
运行结果
Record ID can-NEAR-help Positions 0 ABC123 [(0, 2)] 1 ABC456 [(1, 3), (8, 9)] 2 ABC789 [(2, 3), (3, 4)]
核心改动说明
- 把原函数中用于计数的
result = 0改为空列表result = [] - 将计数操作
result += 1替换为result.append((i, j)),直接存储符合距离要求的词对位置 - 最终返回存储所有有效位置对的列表
内容的提问来源于stack exchange,提问作者tshobe
相关产品推荐
相关产品推荐

