python - 如何在不同情况下使用正则表达式修改熊猫中的字符串
问题描述
我有以下名为 df 的数据框:
Symbol Country Type etc...
0 AG.L UK OS
1 UZ. UK OS
2 DT UK OS
3 XX.L US OS
4 MSFT US OS
5 AAPL US OS
6 DB.S SG OS
我想在框架上执行以下操作。国家 == 'UK',
可能有3种情况。
Case 1: ends with .L,
do nothing
Case 2: ends with .,
add 'L' to the end
Case3: ends with neither . or .L,
add '.L' to the end
只要 Country == 'UK',我希望它以 '.L' 结尾。
所以它应该看起来像这样。
Symbol Country Type etc...
0 AG.L UK OS
1 UZ.L UK OS
2 DT.L UK OS
3 XX.L US OS
4 MSFT US OS
5 AAPL US OS
6 DB.S SG OS
我使用以下代码。
df.loc[df['Country'].eq('UK'),'Symbol'] = df.loc[df['Country'].eq('UK'),'Symbol'].str.replace(r'\.', '.L').str.replace(r'[a-z]$', '.L')
但我明白了
AG.LL
UZ.L
DT
正确的方法是什么?
解决方案
您几乎做对了,但是您在点替换处错过了美元符号,而另一个必须略有不同,因此请尝试:
df.loc[df['Country'].eq('UK'),'Symbol'] = df.loc[df['Country'].eq('UK'),'Symbol'].str.replace(r'^([A-Z]+)$', r'\1.L').str.replace(r'\.$', '.L')
在我的 Python shell 中,它输出:
0 AG.L
1 UZ.L
2 DT.L
Name: Symbol, dtype: object
推荐阅读
- typescript - 10秒间隔的查找速度
- linux - 如何在多字符字符串的 linux 中使用“cut”命令
- javascript - 在 Angular HTML 中显示后端响应
- azure - Azure SignalR withAutomaticReconnect()“错误:连接因错误而断开”...在 Angular8 和 Asp.Net Core 3.1 上
- c# - 不可为空的默认返回空警告
- c# - 如何在 C# 控制台中使链接可点击
- python - 在python中有效地找到方程的根
- python - 如何使 tweepy 与 if/else 语句一起工作?
- firebase - 如何将 Firebase UID 管理为主键
- python - Python:如何使用自定义顺序重新索引分组数据集