我试图了解如何使我的代码更加简洁。我有以下声明,效果很好:
cleaned = dc_listings['price'].str.replace(',', '').str.replace('$', '')
但是,当我尝试使用正则表达式时,如下所示,它不起作用:
cleaned = dc_listings['price'].str.replace(',|$', '')
清理后的变量仍然包含一些“$”条目...我做错了什么?
谢谢!
最佳答案
需要通过 \
转义 $
,因为特殊的 正则表达式字符
- 字符串结尾:
dc_listings = pd.DataFrame({'price':[',ll','j$,']})
cleaned = dc_listings['price'].str.replace(',|\$', '')
print (cleaned)
0 ll
1 j
Name: price, dtype: object
关于python - 如何从数据框中删除多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002891/