为了账号安全,请及时绑定邮箱和手机立即绑定

Pandas:转义列中的所有空格

Pandas:转义列中的所有空格

ITMISS 2023-10-25 10:25:39
我有一个像这样的 pandas 数据框:d = {'col1': ['hi there', 'what are you doing', 'cool'], 'col2': [3, 4, 5]}df = pd.DataFrame(data=d)我使用数据框将命令行参数逐行传递给函数。我的问题是有空格,所以我需要转义它们才能正确地将整行作为参数传递我努力了df.replace(" ", "\ ").head()但这似乎并没有起到任何作用。替换数据框中的所有空格以获得下面的输出的最佳方法是什么?输出:d = {'col1': ['hi\ there', 'what\ are\ you\ doing', 'cool'], 'col2': [3, 4, 5]}df = pd.DataFrame(data=d)
查看完整描述

2 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

打开regex_


out = df.replace(" ", "\ ",regex=True)

                    col1  col2

0              hi\ there     3

1  what\ are\ you\ doing     4

2                   cool     5


查看完整回答
反对 回复 2023-10-25
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

使用.str.replace或.replace(..., regex=True)来替换子字符串。也是\转义字符,所以最好使用原始字符串或其他转义字符:


df['col1'] = df['col1'].str.replace(' ', r'\ ')

输出:


0                hi\ there

1    what\ are\ you\ doing

2                     cool

Name: col1, dtype: object

输出:


                    col1  col2

0              hi\ there     3

1  what\ are\ you\ doing     4

2                   cool     5


查看完整回答
反对 回复 2023-10-25
  • 2 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信