Python 如何将字符串替换为结尾替换为。(期间)?
我正在尝试替换字符串中的Python 如何将字符串替换为结尾替换为。(期间)?,python,pandas,Python,Pandas,我正在尝试替换字符串中的rs. df['Purpose'] = df['Purpose'].str.replace('rs.','') +-------+----------+--------+ | Input | Expected | Output | +-------+----------+--------+ | rs.22 | 22 | 22 | +-------+----------+--------+ | rs32 | rs32 | 2 | +
rs.
df['Purpose'] = df['Purpose'].str.replace('rs.','')
+-------+----------+--------+
| Input | Expected | Output |
+-------+----------+--------+
| rs.22 | 22 | 22 |
+-------+----------+--------+
| rs32 | rs32 | 2 |
+-------+----------+--------+
测试代码:
x = pd.DataFrame(['rs.22', 'rs32'], columns=['Purpose'])
x['Purpose'] = x['Purpose'].str.replace('rs.','')
print('x mod', x)
这将提供以下输出:
x mod Purpose
0 22
1 2
PS:使用regex
[-+]?[.]?[\d]+(?:,\d\d)*[\.]?\d*(?:[eE][-+]?\d+),
无法区分rs.3.5和3.5,但在regex中输出为.3.5,句点“
”几乎匹配所有字符。要匹配文字句点,请使用前面的反斜杠将其转义:
x['Purpose'] = x['Purpose'].str.replace('rs\.','')
请参阅正则表达式howto:这是正确的,您需要使用st替换,因为它有自己的替换功能:-
>>> df
Input
0 rs.22
1 rs321
>>> df['Input'].replace("rs\.","",regex=True)
0 22
1 rs321
Name: Input, dtype: object
>>>
基本上,问题在于默认情况下有
regex=True
,因此它假定传入的模式是正则表达式
您可以使用:
x['Purpose'] = x['Purpose'].str.replace('rs.', '', regex=False)
通常,在正则表达式模式下运行。你有两个简单的选择来绕过它。建议的首选方法是关闭正则表达式:
df['Purpose'] = df['Purpose'].str.replace('rs.', '', regex=False)
另一种方法是转义点,使其匹配实际句点,而不是任何字符。当引入regex
参数时,这是在0.23.0之前的pandas版本中使用的选项:
df['Purpose'] = df['Purpose'].str.replace(r'rs\.', '')
正则表达式匹配通常比简单的字符串比较慢,因此第一个选项的性能更高。请尝试
df['Purpose']=df['Purpose'].str.replace('rs','',Regex=False)
。regex
参数默认为True
,但看起来您只需要常规的Python样式字符串替换。我得到了TypeError:replace()得到了regex的一个意外关键字参数“regex”
错误。第二个工作版本是0.21。1@suku. 这就是为什么我展示了几个备选方案。如果有一个版本没有使用正则表达式,OP的原始版本应该可以使用。@suku您的pandas版本没有正则表达式标志:请参阅,因此,如果无法更新,请使用替代答案。@suku。文件说:新版本0.23.0。