使用字典(下面的示例),需要創建一個新的資料幀列,該列將示例資料幀中的不同列,并且字串中的第一個單詞與字典鍵匹配,將值分配給新列。下面的例子:
dictionary = {'dog':'yellow', 'cat':'black, 'frog':'green', 'horse':'brown'}
原始DF:
ColA:
The dog and horse ate food
Where is the frog?
horse and cat and frog walked together
期望的DF:
ColA: ColB
The dog and horse ate food yellow
Where is the frog? green
horse and cat and frog walked together brown
有什么建議?謝謝!
uj5u.com熱心網友回復:
嘗試:
df["ColB"] = df["ColA"].str.split(expand=True).apply(lambda x: x.str.strip('.?,!":;').map(dictionary)).bfill(axis=1)[0]
ColA ColB
0 The dog and horse ate food yellow
1 Where is the frog? green
2 horse and cat and frog walked together brown
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/318289.html
