如何使用string replace将结尾替换为. (句号)?

2024-05-01 21:52:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从字符串中替换字符串rs.

df['Purpose'] = df['Purpose'].str.replace('rs.','')

+-------+----------+--------+
| Input | Expected | Output |
+-------+----------+--------+
| rs.22 | 22       | 22     |
+-------+----------+--------+
| rs32  | rs32     | 2      |
+-------+----------+--------+

测试规范:

^{pr2}$

这将产生以下输出:

x mod   Purpose
   0      22
   1       2

PS:使用regex [-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?只提取数字的方法无法将rs.3.5区分为3.5,但输出为.3.5


Tags: 字符串规范moddfinputoutputreplaceregex
3条回答

这是正确的一个,你需要用st替换熊猫有自己的替换功能:-在

    >>> df
       Input
    0  rs.22
    1  rs321
   >>> df['Input'].replace("rs\.","",regex=True)
    0       22
    1    rs321
    Name: Input, dtype: object
   >>> 

通常,^{}在regex模式下操作。你有两个简单的选择。@101建议的首选方法是关闭regex:

df['Purpose'] = df['Purpose'].str.replace('rs.', '', regex=False)

另一种方法是转义圆点,以便它匹配实际句点而不是任何字符。当引入regex参数时,在0.23.0之前的pandas版本中使用此选项:

^{pr2}$

Regex匹配通常比简单的字符串比较慢,因此第一个选项可以被重定向,这样性能会更好。在

在regex中,句点“.”几乎匹配所有字符。要匹配文本句点,请使用前面的反斜杠对其进行转义:

x['Purpose'] = x['Purpose'].str.replace('rs\.','')

请参阅regex howto:https://docs.python.org/3/howto/regex.html

相关问题 更多 >