python - 列表和数据框的交集,保留列表的重复项,但显示数据框中列的值
问题描述
找到这个链接和我的工作有点相似。
说我有:
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
推荐阅读
- javascript - 我无法从 D3 力图中正确删除节点
- flutter - 如何在颤动中获取 sqflite 中的列值总数?
- c# - 如何使用 Unity 中的代码将盒子对撞机与网格匹配?
- python - 为什么 requests.get() 不能在 for 循环中工作?
- python - 写入 csv 文件时无法删除难以辨认的内容
- r - 在函数中使用时,for循环不会依次循环通过第一个变量
- sql - 如何从多个表中选择非重复记录
- android - 带有与旧 Android 版本兼容的文件提供程序的清单
- python - 来自archive.ics的“成人数据集”(数据集)的机器学习...... KNeighborsClassifier不会运行
- c - 如何在 C 语言中填补文本之间的空白