[英]Pandas Conditional new column based on period found in other dataframe column
[英]Pandas New Column based on found string in a DataFrame
嘗試將一個DataFrame中的ID值與另一個DataFrame中的字符串列進行匹配,以創建一個新的ID字段。
我有兩個數據框,一個只有文本ID列:
DF1
ID
elf
orc
panda
另一個具有不同ID的數據框,但一個文本列包含第一個DataFrame(DF1)中的ID值:
DF2
AltID Text
1 The orc killed the dwarf
2 The elf lives in the woods
3 The panda eats bamboo
這樣,我可以在第二個數據框(DF2)中創建“新ID”列,如果找到該文本,它將看起來像這樣:
NewID
orc
elf
panda
我應該使用lambda函數還是np.where()?
提前致謝。
編輯:
如果需要完全匹配怎么辦? 例如,我有這行文字,但不想匹配'orc'
AltID Text
4 The orchestra played too long
並希望它為NewID輸出“無”,N / A或類似性質的東西?
直接使用str.extract
:
df2['New ID'] = df2.Text.str.extract('({})'.format('|'.join(df1.ID)), expand=False)
df2
AltID Text New ID
0 1 The orc killed the dwarf orc
1 2 The elf lives in the woods elf
2 3 The panda eats bamboo panda
一個小把戲。
df2.Text.replace(dict(zip(df1.ID,df1.index)),regex=True).map(df1.ID)
Out[1004]:
0 orc
1 elf
2 panda
Name: Text, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.