2 回答

TA貢獻(xiàn)1872條經(jīng)驗 獲得超4個贊
這應(yīng)該做你想做的:
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}
編輯:
要反映列內(nèi)的列表,請參閱此嵌套理解:
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貢獻(xiàn)1804條經(jīng)驗 獲得超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
或者,如果您總是有固定數(shù)量的單詞,則可以拆分為多個系列并使用pd.DataFrame.applymap:
df['total'] = pd.DataFrame(df['words'].tolist()).applymap(d.get).sum(1).astype(int)
添加回答
舉報