发现这个链接和我的工作有些相似。
假设我有:
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]
对如何实现这一点有什么想法吗?非常感谢。
你不需要熊猫。首先修改你的字典,把这些词作为关键字,然后使用一个推导式:
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