python - 如何通过识别模式替换具有不同名称的列的条目?
问题描述
我有一个列,假设'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
解决方案
您可以使用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-3.x - 使用 Groupby 多列 Pandas 获取正值和负值计数
- python - Python Flask 中的各种错误
- javascript - 比较两个数组时无法正确找到重复项
- neo4j - neo4j Cypher:关系未按预期工作
- python - 是否可以将矢量图形放入视频中?
- python - 如何在我的神经网络中应用从梯度下降到权重的变化?
- android - 如何使用 androidx 发送内容视图以进行数据绑定?
- google-apps-script - 用于在 Google 表格中附加数据范围的 Google App 脚本
- perl - 无法从 Mojolicious 路由处理程序内部连接到外部 websocket
- python - 找不到满足 opencv-python 要求的版本