我有一个列让我们说 'Match Place'
,其中有像 'MANU @ POR'
、'MANU vs. UTA'
这样的条目code>、'MANU @ IND'
、'MANU vs. GRE'
等。所以我的专栏条目中有 3 个内容,第一个名称是 MANU
即第一个国家/地区代码,第二个是 @/vs.
,第三个也是第二个国家/地区名称。所以我想做的是,如果 '@'
出现在我的专栏的任何条目中,我想将其更改为 'away'
并且如果 'vs.'
替换了 'home'
的整个条目,例如 'MANU @ POR' 应该更改为 'away'
并且 'MANU vs. GRE' 应该更改到“家”
尽管我使用 for, if, else 写了一些代码来这样做,但是计算它花费的时间太长了,我的总行数是 30697 那么有没有其他方法可以减少时间 下面我向您展示我的代码 请帮忙
for i in range(len(df)):
if is_na(df['home/away'][i]) == True:
temp = (df['home/away'][i]).split()
if temp[1] == '@':
df['home/away'][i] = 'away'
else:
df['home/away'][i] = 'home
最佳答案
您可以使用 np.select
分配多个条件:
s=df['Match Place'].str.split().str[1] #select the middle element
c1,c2=s.eq('@'),s.eq('vs.') #assign conditions
np.select([c1,c2],['away','home']) #assign this to the desired column
#array(['away', 'home', 'away', 'home'], dtype='<U11')
关于python - 如何通过识别模式来替换具有不同名称的列的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125740/