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

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


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


此代码为列中的一行生成预期结果,但是,如果我尝试将其应用于多列,则会出现“不可哈希类型列表”错误。


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]


梵蒂冈之花
浏览 234回答 2
2回答

守着一只汪

这应该做你想做的:import pandas as pddf = 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]然后,您可以将 list_totals 作为列添加到您的 pd。

三国纷争

一种解决方案是使用collections.Counter和列表理解:from collections import Counterd = 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  total0    [cow, bird, cat]      51  [red, blue, green]      32    [low, high, med]      9或者,如果您总是有固定数量的单词,则可以拆分为多个系列并使用pd.DataFrame.applymap:df['total'] = pd.DataFrame(df['words'].tolist()).applymap(d.get).sum(1).astype(int)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python