【问题标题】:pandas: remove dot only if it occurs after a digit in a stringpandas:仅当它出现在字符串中的数字之后才删除点
【发布时间】:2020-05-21 08:16:08
【问题描述】:

我有一个如下所示的数据框:

df=  pd.DataFrame(["I", "have", "5.", "apples", "."]
                 columns=['words'])

我只想删除数字后面的点,而不是句末的点。 (5.--> 5)

我试过了

df["Words"].str.replace("\d.", "\d", regex=True)

但它会发送错误。

【问题讨论】:

    标签: python regex string pandas dataframe


    【解决方案1】:

    以下应该可以工作 - 我们需要在正则表达式中使用捕获组,以便我们知道应该用什么值替换初始值。此外,我们需要使用原始字符串文字来转义正则表达式字符串中的反斜杠。

    >>> df = pd.DataFrame(["I", "have", "5.", "apples", "."],
                      columns=['words'])
    >>> df["words"].str.replace(r"(\d)\.", r"\1")
    0         I
    1      have
    2         5
    3    apples
    4         .
    Name: words, dtype: object
    

    【讨论】:

      【解决方案2】:

      我们需要

      df["words"].str.replace(r"^(\d+)\.$", r"\1")
      

      这也匹配更长的数字,并确保最后一个字符是点而不是任何东西。

      CDJB的答案并不完全正确:

      df = pd.DataFrame(["I", "have", "50a", "apples", "."],
                        columns=['words'])
      [ins] In [12]: df["words"].str.replace(r"(\d).", r"\1")
      Out[12]:
      0         I
      1      have
      2        5a
      3    apples
      4         .
      Name: words, dtype: object
      

      【讨论】:

        猜你喜欢
        • 2019-01-13
        • 1970-01-01
        • 1970-01-01
        • 2012-06-09
        • 1970-01-01
        • 2013-08-21
        • 1970-01-01
        • 1970-01-01
        • 2017-08-25
        相关资源
        最近更新 更多