我有一個單詞串列和一個資料框
data = {'test':['dog is happy', 'dog is hap', 'dog is hap']}
df = pd.DataFrame(data)
list = ['dog', 'hap', 'happy']
df
test
0 dog is happy
1 dog is hap
2 doggy is hap
我想添加一列,讓我們稱之為“單詞”,這樣如果它出現在行中,它將查找整個單詞。如果是,我想將該詞添加到詞列。我要求的輸出是
df
test words
0 dog is happy dog happy
1 dog is hap dog hap
2 doggy is hap hap
我發現 SO 上的一些帖子會在第一行回傳“hap”,因為“happy”以“hap”開頭。(與第三行中的 dog 和 doggy 相同的概念)我還找到了在 words 列中回傳 True/False 的示例,但我希望在該列中有實際的單詞。感謝并很高興澄清任何混淆點。
uj5u.com熱心網友回復:
這很簡單,使用set.intersection:
>>> words = {'dog', 'hap', 'happy'}
>>> df["matches"] = df["test"].str.split().apply(set(words).intersection)
>>> df
test matches
0 dog is happy {happy, dog}
1 dog is hap {dog, hap}
2 doggy is hap {hap}
當然,如果您希望您的匹配按特定順序或作為單個空格分隔的單詞,這是行不通的,但您可能不會這樣做......
uj5u.com熱心網友回復:
這是使用的解決方案str.findall()
df.assign(words = df['test'].str.findall('|'.join([r'\b{}\b'.format(i) for i in l])).str.join(' '))
輸出:
test words
0 dog is happy dog happy
1 dog is hap dog hap
2 doggy is hap hap
uj5u.com熱心網友回復:
我希望這是你想要的。
filter_words = ['dog', 'happy', 'hap']
def add_words(x):
return ' '.join([
token
for token in x.split(' ')
if token in filter_words
])
df['words'] = df['test'].apply(lambda x: add_words(x))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/472479.html
下一篇:加快從熊貓資料框中讀取內容的速度
