为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梵蒂冈之花 2021-07-30 02:25:21
列表的数据框列(系列)可以用作字典中的条件检查吗?我有一列单词列表(拆分推文),我想将它们提供给词汇词典以查看它们是否都存在 - 如果不存在,我想跳过它,继续然后运行对现有单词的函数。此代码为列中的一行生成预期结果,但是,如果我尝试将其应用于多列,则会出现“不可哈希类型列表”错误。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   words0   5   [cow, bird, cat]1   3   [red, blue, green]2   9   [low, high, med]
查看完整描述

2 回答

?
守着一只汪

TA贡献1872条经验 获得超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]

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


查看完整回答
反对 回复 2021-08-03
?
三国纷争

TA贡献1804条经验 获得超7个赞

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


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.DataFrame.applymap:


df['total'] = pd.DataFrame(df['words'].tolist()).applymap(d.get).sum(1).astype(int)


查看完整回答
反对 回复 2021-08-03
  • 2 回答
  • 0 关注
  • 233 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号