![](/img/trans.png)
[英]find a value in a dataframe and add precedent column value in a new column in pandas
[英]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.match
与regex
和正则表达式标志不区分大小写( ?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.