首页 > 解决方案 > 如何通过识别模式替换具有不同名称的列的条目?

问题描述

我有一个列,假设'Match Place'其中有 , , 等条目'MANU @ POR''MANU vs. UTA'所以'MANU @ IND''MANU vs. GRE'的列中有 3 个条目,第一个名称是MANU第一个国家代码,第二个是@/vs.,第三个是第二个国家/地区名称。所以我想做的是,如果'@'出现在我想要更改的列的任何条目中'away',如果'vs.'出现替换整个条目,'home'例如“MANU @ POR”应该更改为'away',“MANU vs. GRE”应该更改为'home'

尽管我使用 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

标签: pythonstringpandas

解决方案


您可以使用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')

推荐阅读