首页 > 解决方案 > 列表和数据框的交集,保留列表的重复项,但显示数据框中列的值

问题描述

找到这个链接和我的工作有点相似。

说我有:

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)
items = set(df['words'])

found = [i for i in x if i in items] 
print(found)

结果是:['the', 'the', 'and', 'heart', 'heart']

我希望能够得到单词的对应值,我被卡住了。我想要的结果是这样的:

[3,3,4,1,1]

关于如何实现这一目标的任何想法?将不胜感激。

标签: pythondataframeintersection

解决方案


你不需要熊猫。首先修改您的字典以将单词作为键,然后使用理解:

y2 = dict(zip(*y.values()))
[y2[i] for i in x if i in y2]

输出:[3,3,4,1,1]

pandas 中的(效率低得多)等价物是:

s = df.set_index('words')['values']
pd.Series(x).map(s).dropna()

输出:

0    3.0
1    3.0
2    4.0
5    1.0
6    1.0
dtype: float64

推荐阅读