首页 > 解决方案 > 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。

标签: pythonstringpandas

解决方案


$是正则表达式中的特殊字符,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)]

推荐阅读