python - Pandas - 使用对象 DType 过滤 Col 用于几个条件
问题描述
我在对象 dtype 的 df 中有一个列。我在筛选价格字段中带有 $xxxxxxx 和 CAD 的人时遇到了一些问题。
Price
$1,000,000
$2,000,000
$700,000
1,234,567 CAD
$111,111
3,000,000 EUR
Inquire
$500,000
Auction
我试过这个没有成功:
df = df[(df['Price'].str.contains('$')) | (df['Price'].str.contains('CAD'))]
如果我只想要 CAD,这可行:
df = df[df['Price'].str.contains('CAD')
但是,如何仅用 $ 和 CAD 获得所有值?因此,在我上面的示例数据(欧元、询价、拍卖)中删除 3。
解决方案
$
是正则表达式中的特殊字符,pd.Series.str.contains
默认启用正则表达式。您可以通过以下方式禁用正则表达式、使用re.escape
或转义\
:
import re
# choose one of the below
m1 = df['Price'].str.contains('$', regex=False) # disable regex, most efficient
m1 = df['Price'].str.contains(re.escape('$')) # escape via re.escape
m1 = df['Price'].str.contains('\$') # escape via \
# turn off regex when not required for a performance boost
m2 = df['Price'].str.contains('CAD', regex=False)
print(df[m1 | m2])
Price
0 $1,000,000
1 $2,000,000
2 $700,000
3 1,234,567 CAD
4 $111,111
7 $500,000
最适应的是将正则表达式与re.escape
. 例如:
L = ['$', 'CAD']
search_str = '|'.join(map(re.escape, L))
df = df[df['Price'].str.contains(search_str)]
推荐阅读
- android - 无法使用 RETROFIT + COROUTINE 获取数据
- javascript - 如何将值插入到 PostgreSQL 中特定行的列中?
- sql - 出现时如何在两个破折号后返回字符
- wordpress - 您可以在管理面板的分类关系字段中显示 ACF 字段吗?
- php - 从 api 数组中获取数据
- google-cloud-platform - GCP Composer (Autoscaling) 环境错误 - “某些 GKE pod 无法正常运行”
- flutter - Flutter stack + 容器来构建类似火种的东西
- node.js - NodeJS ImageMagick 如何转换具有透明背景的图像
- proxy - APACHE - proxypass 问题(排除带有 wordpress 安装的子文件夹)
- python - 是否可以在 Python Tkinter 的屏幕中间居中放置一个框架?