我在df中有一个带有对象dtype的列。我有一些困难的过滤只是那些与$xxxxxxx和计算机辅助设计在价格领域。
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'))]如果我只想要民航处,这是可行的:
df = df[df['Price'].str.contains('CAD')但是,如何用$和CAD来获得所有的值?因此,删除3在我的样本数据以上(欧元,查询,拍卖)。
发布于 2019-01-22 16:47:26
尝试使用\作为转义字符,|用于或操作。默认使用regex的模式的pd.Series.str.contains:
df[df['Price'].str.contains('\$|CAD')]输出:
Price
0 $1,000,000
1 $2,000,000
2 $700,000
3 1,234,567 CAD
4 $111,111
7 $500,000而且,如果您也想要捕获“EUR”,请使用另一个|
df[df['Price'].str.contains('\$|CAD|EUR')]发布于 2019-01-22 16:44:47
$是regex中的一个特殊字符,pd.Series.str.contains默认启用regex。您可以禁用regex、使用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最适合使用regex的是re.escape。例如:
L = ['$', 'CAD']
search_str = '|'.join(map(re.escape, L))
df = df[df['Price'].str.contains(search_str)]发布于 2019-01-22 17:25:38
我看到,我们已经有了专家的答案,但这只是为了子孙后代而采取的另一种方法。
>>> df[ df['Price'].str.startswith('$') | df['Price'].str.endswith('CAD') ]
Price
0 $1,000,000
1 $2,000,000
2 $700,000
3 1,234,567 CAD
4 $111,111
7 $500,000https://stackoverflow.com/questions/54312720
复制相似问题