我目前有一个Pandas DataFrame,其中包含许多转义字符中使用的反斜杠。例如,有些字符串的格式为'Michael\'s dog'
。
当我使用pandas.DataFrame.to_csv
将此DataFrame保存到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
是行不通的。
答案 0 :(得分:0)
您可以使用string.replace()
。
'Michael\'s dog'.replace("\\", "")
双反斜杠可避免反斜杠。
答案 1 :(得分:0)
不要使用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