我有一个像这样的 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 回答
![?](http://img1.sycdn.imooc.com/545850c80001ebf202200220-100-100.jpg)
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
打开regex_
out = df.replace(" ", "\ ",regex=True)
col1 col2
0 hi\ there 3
1 what\ are\ you\ doing 4
2 cool 5
![?](http://img1.sycdn.imooc.com/545862770001a22702200220-100-100.jpg)
叮当猫咪
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
添加回答
举报
0/150
提交
取消