You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

列表与DataFrame求交集保留列表重复值并获取对应列值的方法

实现方案

你可以先将y中的词和对应数值转换为映射字典,遍历x的过程中直接筛选并取值即可,无需单独先筛选匹配的词,示例代码如下:

x = ['the', 'the', 'and', 'a', 'apple', 'heart', 'heart']
y = {'words': ['the', 'belt', 'computer', 'heart','and'],'values':[3,2,1,1,4]}

# 构建词到数值的映射字典
word_value_map = dict(zip(y['words'], y['values']))
# 遍历x,匹配到的词直接取对应数值
result = [word_value_map[word] for word in x if word in word_value_map]

print(result)

运行输出就是你期望的[3, 3, 4, 1, 1]。

如果你要沿用已有的pandas写法,只需要把词集合替换为索引映射即可,修改后代码如下:

import pandas as pd

x = ['the', 'the', 'and', 'a', 'apple', 'heart', 'heart']
y = {'words': ['the', 'belt', 'computer', 'heart','and'],'values':[3,2,1,1,4]}

df = pd.DataFrame.from_dict(y)
# 构建词到数值的映射
word_value_map = df.set_index('words')['values'].to_dict()

result = [word_value_map[i] for i in x if i in word_value_map]
print(result)

内容的提问来源于stack exchange,提问作者axia_so2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:45:03