[英]Update dataframe values that match a regex condition and keep remaining values intact
The following is an excerpt from my dataframe:以下是我的数据框的摘录:
In[1]: df
Out[1]:
LongName BigDog
1 Big Dog 1
2 Mastiff 0
3 Big Dog 1
4 Cat 0
I want to use regex to update BigDog values to 1 if LongName is a mastiff.如果 LongName 是獒犬,我想使用正则表达式将 BigDog 值更新为 1。 I need other values to stay the same.
我需要其他价值观保持不变。 I tried this, and although it assigns 1 to mastiffs, it nulls all other values instead of keeping them intact.
我试过了,虽然它为獒犬分配了 1,但它会将所有其他值归零,而不是保持它们完好无损。
def BigDog(longname):
if re.search('(?i)mastiff', longname):
return '1'
df['BigDog'] = df['LongName'].apply(BigDog)
I'm not sure what to do, could anybody please help?我不知道该怎么办,有人可以帮忙吗?
You don't need a loop or apply, use str.match
with DataFrame.loc
:您不需要循环或应用,将
str.match
与DataFrame.loc
str.match
使用:
df.loc[df['LongName'].str.match('(?i)mastiff'), 'BigDog'] = 1
LongName BigDog
1 Big Dog 1
2 Mastiff 1
3 Big Dog 1
4 Cat 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.