簡體   English   中英

使用正則表達式在不同列的熊貓數據框中查找單詞並創建新值

[英]Find words and create new value in different column pandas dataframe with regex

假設我有一個包含以下內容的數據框:

df = pd.DataFrame({'Name':['John', 'Alice', 'Peter', 'Sue'],
                   'Job': ['Dentist', 'Blogger', 'Cook', 'Cook'], 
                  'Sector': ['Health', 'Entertainment', '', '']})

我想找到所有“廚師”,無論是否為大寫字母,並將它們分配給名為“美食”的值的“部門”列,我該怎么做? 並且不覆蓋“部門”列中的其他條目? 謝謝!

這是一種方法:

df.loc[df.Job.str.lower().eq('cook'), 'Sector'] = 'gastronomy'

print(df)

    Name      Job         Sector
0   John  Dentist         Health
1  Alice  Blogger  Entertainment
2  Peter     Cook     gastronomy
3    Sue     Cook     gastronomy

使用Series.str.matchregex和正則表達式標志不區分大小寫( ?i ):

df.loc[df['Job'].str.match('(?i)cook'), 'Sector'] = 'gastronomy'

輸出


    Name      Job         Sector
0  John   Dentist  Health       
1  Alice  Blogger  Entertainment
2  Peter  Cook     gastronomy   
3  Sue    Cook     gastronomy 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM