python - 如何从数据框中删除多个字符

标签 python pandas

我试图了解如何使我的代码更加简洁。我有以下声明,效果很好:

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/

相关文章:

python - 带有 JOIN 和 GROUP BY SQL 查询的 Django COUNT

python - 在 Python 中开发递归函数

python - 带有 bool OR 的 Pandas groupby

python-3.x - 在没有索引的 Jupyter 中显示完整的 Pandas 数据框

获取索引的pythonic方式,值== 1的列

python - 在扩展 CB 上按用户显示内容过滤器

python - 修改pandas数据框中的csv数据

python - 在 Mac OS X 上安装 Pandas for Python 时出错

python - Pandas 的 Matplotlib 堆积直方图被一条奇怪的线切割

python - 在Python中读取巨大的MySQL表的最快方法