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

Python 检查字典[pandas]中是否存在列值,python,pandas,dictionary,Python,Pandas,Dictionary,列表的数据框列(系列)能否用作字典中的条件检查 我有一列单词列表(拆分推文),我想将它们输入vocab字典,看看它们是否都存在——如果不存在,我想跳过它,继续,然后对现有单词运行函数 此代码为列中的一行生成预期结果,但是,如果我尝试将其应用于多个列,则会出现“unhashable type list”错误 w2v_sum = w2v[[x for x in train['words'].values[1] if x in w2v.vocab]].sum() 使用可复制的示例进行编辑: df =

列表的数据框列(系列)能否用作字典中的条件检查

我有一列单词列表(拆分推文),我想将它们输入vocab字典,看看它们是否都存在——如果不存在,我想跳过它,继续,然后对现有单词运行函数

此代码为列中的一行生成预期结果,但是,如果我尝试将其应用于多个列,则会出现“unhashable type list”错误

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}
所需输出为总输出(字典中单词的总和):


这应该满足您的要求:

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}
编辑:

要反映列中的列表,请参见以下内容:

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]
from collections import Counter

d = Counter({'cow':1,'bird':4,'red':1,'blue':1,'green':1,'high':6,'med':3})

df['total'] = [sum(map(d.__getitem__, L)) for L in df['words']]

print(df)

                words  total
0    [cow, bird, cat]      5
1  [red, blue, green]      3
2    [low, high, med]      9
然后,您可以将列表汇总作为一列添加到pd中。

一种解决方案是使用和列表理解:

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]
from collections import Counter

d = Counter({'cow':1,'bird':4,'red':1,'blue':1,'green':1,'high':6,'med':3})

df['total'] = [sum(map(d.__getitem__, L)) for L in df['words']]

print(df)

                words  total
0    [cow, bird, cat]      5
1  [red, blue, green]      3
2    [low, high, med]      9
或者,如果您的字数始终固定,则可以将其拆分为多个系列并使用:


你能加一些吗data@J.Doe用数据编辑我在每个条目中都有一个列表,而不仅仅是一个单词,所以我仍然收到一个不可修复的类型列表错误。我调整了答案以反映您的数据。