如何将文件字符串与DataFrame的position列匹配并输出对应vector?
问题描述
需要将文件中的每行字符串与DataFrame的position列匹配,匹配成功则输出该行字符串及其对应的vector列内容。
文件内容示例:
0100000000 0001000000
期望输出格式:
0100000000 01 0001000000 01
现有基础代码:
import pandas as pd data_f = pd.DataFrame( {'position': {0: '1000000000', 1: '0100000000', 2: '0010000000', 3: '0001000000', 4: '0000100000', 5: '0000010000'}, 'vector': {0: '10', 1: '01', 2: '10', 3: '01', 4: '01', 5: '01'}}) with open("/test_2vec/example_vec61.txt", "r") as f1: for vec in f1: print(vec)
解决方案
可以先将DataFrame的position和vector转换为字典实现快速查找,同时处理文件每行的换行符确保匹配准确,修改后的代码如下:
import pandas as pd data_f = pd.DataFrame( {'position': {0: '1000000000', 1: '0100000000', 2: '0010000000', 3: '0001000000', 4: '0000100000', 5: '0000010000'}, 'vector': {0: '10', 1: '01', 2: '10', 3: '01', 4: '01', 5: '01'}}) # 构建position到vector的映射字典,提升查找效率 pos_to_vec = dict(zip(data_f['position'], data_f['vector'])) with open("/test_2vec/example_vec61.txt", "r") as f1: for line in f1: # 去除行尾换行符及空白字符,避免匹配失败 pos_str = line.strip() # 检查当前行字符串是否存在于映射中 if pos_str in pos_to_vec: print(f"{pos_str} {pos_to_vec[pos_str]}")
关键说明
dict(zip(data_f['position'], data_f['vector'])):把DataFrame的两列打包成键值对字典,将position作为键、vector作为值,单次查找复杂度为O(1),比循环遍历DataFrame更高效。line.strip():移除每行字符串的换行符、空格等空白字符,解决文件读取时自带换行符导致的匹配失效问题。- 匹配成功时按照指定格式输出目标内容。
内容的提问来源于stack exchange,提问作者Vykov
相关产品推荐
相关产品推荐

