Pandas:转义列中的所有空格

我有一个像这样的 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)


ITMISS
浏览 109回答 2
2回答

翻过高山走不出你

打开regex_out = df.replace(" ", "\ ",regex=True)                    col1  col20              hi\ there     31  what\ are\ you\ doing     42                   cool     5

叮当猫咪

使用.str.replace或.replace(..., regex=True)来替换子字符串。也是\转义字符,所以最好使用原始字符串或其他转义字符:df['col1'] = df['col1'].str.replace(' ', r'\ ')输出:0                hi\ there1    what\ are\ you\ doing2                     coolName: col1, dtype: object输出:                    col1  col20              hi\ there     31  what\ are\ you\ doing     42                   cool     5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python