Skip to main content
 首页 » 编程设计

python之检查字典中是否存在列值 [pandas]

2024年12月31日9kevingrace

列表的数据框列(系列)可以用作字典中的条件检查吗?

我有一列单词列表(拆分推文),我想将其提供给词汇词典以查看它们是否都存在 - 如果不存在,我想跳过它,继续然后对现有单词运行一个函数。

此代码为列中的一行生成了预期的结果,但是,如果我尝试将它应用于多个列,我会收到“无法散列的类型列表”错误。

w2v_sum = w2v[[x for x in train['words'].values[1] if x in w2v.vocab]].sum() 

使用可重现的示例进行编辑:

df = pd.DataFrame(data={'words':[['cow','bird','cat'],['red','blue','green'],['low','high','med']]}) 
 
d = {'cow':1,'bird':4,'red':1,'blue':1,'green':1,'high':6,'med':3} 

期望的输出是总计(字典中单词的总和):

total   words 
0   5   [cow, bird, cat] 
1   3   [red, blue, green] 
2   9   [low, high, med] 

请您参考如下方法:

这应该做你想做的:

import pandas as pd 
df = pd.DataFrame(data={'words':[['cow','bird','cat'],['red','blue','green'],['low','high','med']]}) 
 
d = {'cow':1,'bird':4,'red':1,'blue':1,'green':1,'high':6,'med':3} 

编辑:

要反射(reflect)列内的列表,请参阅此嵌套理解:

list_totals = [[d[x] for x in y if x in d] for y in df['words'].values] 
list_totals = [sum(x) for x in list_totals] 
list_totals 
[5, 3, 9] 

然后您可以将 list_totals 作为列添加到您的 pd。