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。

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)
添加回答
举报