python - 将 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
行不通的。
解决方案
不要使用 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
推荐阅读
- php - 引导模式没有获取用户 ID
- python-3.x - Chrome 驱动程序错误 selenium 消息:会话未从断开连接创建:无法连接到渲染器
- javascript - Discord.js 显示状态中的禁令数量
- php - ffmpeg 命令无法正确捕获移动视频图像。总是得到拉伸图像
- java - 我正在尝试在 java 中使用 CertAndKeyGen 我尝试导入 sun.security.x509.CertAndKeyGen.ALL sun 包库显示错误
- android-ndk - SENSOR_FRAME_DURATION 未更改为 1/60
- c++ - 为什么在运行时而不是在编译时使用 constexpr 初始化变量
- sonos - 播放 Sonos Group 中播放列表的特定曲目
- android - 有没有办法检测我的 Android TV 遥控器是否有麦克风?
- audio - 使用 ffmpeg 对 mkv 进行缩减、色调映射、缩混和重新编码