字符串替换结构更换vsPandas结构代表

2024-06-13 13:18:38 发布

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

我需要将反斜杠替换为其他内容,并编写以下代码来测试基本概念。工作正常:

test_string = str('19631 location android location you enter an area enable quick action honeywell singl\dzone thermostat environment control and monitoring')
print(test_string)

test_string = test_string.replace('singl\\dzone ','singl_dbl_zone ')
print(test_string)

19631 location android location you enter an area enable quick action honeywell singl\dzone thermostat environment control and monitoring
19631 location android location you enter an area enable quick action honeywell singl_dbl_zone thermostat environment control and monitoring

但是,我有一个熊猫df充满了这些(重新配置)字符串,当我试图操作df时,它不起作用。在

^{pr2}$

反斜杠仍然存在!在

323096  you enter an area android location location environment control and monitoring honeywell singl\dzone thermostat enable quick action 

Tags: testyouanstringenableactionarealocation
2条回答

str.replace和{}之间有区别。前者接受子字符串替换,后者接受正则表达式模式。在

使用str.replace,您需要传递一个原始字符串。在

df['col'] = df['col'].str.replace(r'\\d', '_dbl_')

我认为去掉反斜杠会更容易:

In [165]: df
Out[165]:
  constructed_recipe
0       singl\dzone

In [166]: df['constructed_recipe'] = df['constructed_recipe'].str.replace(r'\\', '')

In [167]: df
Out[167]:
  constructed_recipe
0        singldzone

相关问题 更多 >