【问题标题】:How to use regex to modify a string in pandas in different cases如何在不同情况下使用正则表达式修改熊猫中的字符串
【发布时间】:2020-09-23 09:55:09
【问题描述】:

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

正确的做法是什么?

【问题讨论】:

  • 是否可以在 python 中将 '([^L])$' 替换为 $1L?因此,如果最后一个字符不是 L,请在最后一个字符上添加一个 L。不知道 python 中捕获组和反向引用的确切语法。你必须自己找出答案。
  • DB.S 不会受到影响,因为它不在英国
  • 抱歉,我的编辑使您的评论过时了。您对不在英国的 DB.S 是正确的,但这是替换中的错误。如果将所有句点替换为 .L,这将对中间有句点的英国符号产生影响。这就是 AG.LL 的原因:句点被替换为 .L

标签: python regex pandas string replace


【解决方案1】:

您几乎是正确的,但是您在点替换时错过了美元符号,而另一个必须略有不同,所以请尝试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2021-03-06
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2018-09-14
    • 2020-05-25
    相关资源
    最近更新 更多