首页 > 解决方案 > 如何在不同情况下使用正则表达式修改熊猫中的字符串

问题描述

我有以下名为 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      

正确的方法是什么?

标签: pythonregexpandasstringreplace

解决方案


您几乎做对了,但是您在点替换处错过了美元符号,而另一个必须略有不同,因此请尝试:

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

推荐阅读