第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

梵蒂岡之花 2021-07-30 02:25:21
列表的數(shù)據(jù)框列(系列)可以用作字典中的條件檢查嗎?我有一列單詞列表(拆分推文),我想將它們提供給詞匯詞典以查看它們是否都存在 - 如果不存在,我想跳過它,繼續(xù)然后運行對現(xiàn)有單詞的函數(shù)。此代碼為列中的一行生成預(yù)期結(jié)果,但是,如果我嘗試將其應(yīng)用于多列,則會出現(xiàn)“不可哈希類型列表”錯誤。w2v_sum = w2v[[x for x in train['words'].values[1] if x in w2v.vocab]].sum()使用可重現(xiàn)的示例進(jìn)行編輯: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貢獻(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。


查看完整回答
反對 回復(fù) 2021-08-03
?
三國紛爭

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)


查看完整回答
反對 回復(fù) 2021-08-03
  • 2 回答
  • 0 關(guān)注
  • 247 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號