首页 > 解决方案 > 将 DataFrame 保存到 CSV 时删除反斜杠转义字符

问题描述

我目前有一个 Pandas DataFrame,其中包含许多用于转义字符的反斜杠。例如,有格式为 的字符串'Michael\'s dog'

当我使用 将此 DataFrame 保存到 CSV 文件pandas.DataFrame.to_csv时,我想去掉这些反斜杠,以便 CSV 文件中的条目"Michael's dog"只是

有没有一种简单的方法可以通过利用函数或方法来做到这一点?我试图通过原始 DataFrame 并手动进行更改,但我无法摆脱必须有更有效方法的感觉。

谢谢你。

编辑

很抱歉造成混淆,也许我应该在我原来的问题中更具体。

我遇到问题的数据是以下形式:

[' [\'Mazda\', \'it\', "Mazda \'s", \'its\', \'its\', "Mazda \'s"]',
 " ['the 2019 Mazda3', 'the 2019 Mazda3', 'it', 'the 2019 Mazda3', 'The 2019 Mazda3', 'its']",
 " ['the car', 'its']",
 ' [\'the Japanese automaker\', "the brand \'s"]']

如您所见,数据在技术上是一个列表而不是字符串,这意味着简单地使用是replace行不通的。

标签: pythonpandascsvdataframe

解决方案


不要使用 str.replace,它只会替换每个 '\' 字符。

改用这个:

df.ColumnName.str.decode('unicode_escape')

测试:

>>> data = {'Name':['Tom\\\\\'', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} 
>>> df = pd.DataFrame(data)
>>> df.Name.str.decode('unicode_escape')
0    Tom\'
1     nick
2    krish
3     jack
Name: Name, dtype: object

作者测试:

>>> data
{'Name': [' [\'Mazda\', \'it\', "Mazda \'s", \'its\', \'its\', "Mazda \'s"]', " ['the 2019 Mazda3', 'the 2019 Mazda3', 'it', 'the 2019 Mazda3', 'The 2019 Mazda3', 'its']", " ['the car', 'its']", ' [\'the Japanese automaker\', "the brand \'s"]']}
>>> df = pd.DataFrame(data)
>>> df.Name.str.decode('unicode_escape')
0     ['Mazda', 'it', "Mazda 's", 'its', 'its', "Ma...
1     ['the 2019 Mazda3', 'the 2019 Mazda3', 'it', ...
2                                   ['the car', 'its']
3           ['the Japanese automaker', "the brand 's"]
Name: Name, dtype: object

来源: https ://stackoverflow.com/a/14820462/6741053


推荐阅读