以下是我的数据帧的摘录:
In[1]: df
Out[1]:
LongName BigDog
1 Big Dog 1
2 Mastiff 0
3 Big Dog 1
4 Cat 0
如果 LongName 是獒犬,我想使用正则表达式将 BigDog 值更新为 1。我需要其他值保持不变。我试过这个,虽然它为獒犬分配了 1,但它将所有其他值清空,而不是保持它们完好无损。
def BigDog(longname):
if re.search('(?i)mastiff', longname):
return '1'
df['BigDog'] = df['LongName'].apply(BigDog)
我不知道该怎么办,有人可以帮忙吗?
你不需要循环或应用,str.match
与DataFrame.loc
一起使用:
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