【问题标题】:How to replace a specific character which occurs between 2 characters?如何替换出现在两个字符之间的特定字符?
【发布时间】:2019-10-28 19:27:55
【问题描述】:

我有一个具有以下值的熊猫系列:

import pandas as pd
input_series = pd.Series(['9009.00', '909.99', '9999.00', '9000.00', '900900900.00', '9900.09'])

我想生成一个如下所示的系列:

预期系列

9999.00
999.99
9999.00
9000.00
999999900.00
9999.99

任务是替换出现在两个九 (9) 之间的所有零 (0)。 我曾尝试使用 pandas 的 str.replace util,但没有成功。

【问题讨论】:

    标签: regex python-3.x pandas


    【解决方案1】:

    使用自定义函数查找第一个 9 by find 和最后一个 9 by rfind 并仅替换此子字符串:

    input_series = pd.Series(['9009.00', '909.99', '9999.00', '9000.00',
                              '900900900.00', '9900.09'])
    
    def rep(x):
        r = x[x.find('9'):x.rfind('9')+1]
        return x.replace(r, r.replace('0','9'))
    
    input_series = input_series.apply(rep)
    print (input_series)
    0         9999.00
    1          999.99
    2         9999.00
    3         9000.00
    4    999999900.00
    5         9999.99
    dtype: object
    

    【讨论】:

      【解决方案2】:
      >>> input_series = pd.Series(['9009.00', '909.99', '9999.00', '9000.00', '900900900.00'])
      >>> 
      >>> df = pd.DataFrame()
      >>> df['input'] = input_series
      >>> df['extract'] = df['input'].str.extract('(9[09]+9)').fillna('')
      >>> df['out'] = df.apply(lambda x: x['input'].replace(x['extract'], x['extract'].replace('0', '9')), axis=1)
      >>> df
                input  extract           out
      0       9009.00     9009       9999.00
      1        909.99      909        999.99
      2       9999.00     9999       9999.00
      3       9000.00                9000.00
      4  900900900.00  9009009  999999900.00
      

      附言

      对于添加的新案例,即“9900.09”到“9999.99”

      将正则表达式更新为 (9[09.]+9)

      【讨论】:

        猜你喜欢
        • 2017-04-08
        • 1970-01-01
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多