【问题标题】:Pandas - Filter Col with Object DType for a Couple ConditionsPandas - 具有对象 DType 的过滤列,用于几个条件
【发布时间】:2019-06-16 04:28:00
【问题描述】:

我在对象 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(欧元、询价、拍卖)。

【问题讨论】:

  • 我尝试了其他一些方法,例如将 $ 替换为 USD,然后像上面一样过滤 USD 和 CAD,但这不起作用。我还尝试了其他一些方法。

标签: python string pandas


【解决方案1】:

尝试将\ 用于转义字符,将| 用于或操作。 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

而且,如果您还想抓住那个“欧元”,请使用另一个 |

df[df['Price'].str.contains('\$|CAD|EUR')]

【讨论】:

  • 谢谢!这只是添加一个简单的字符!
【解决方案2】:

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

【讨论】:

  • 谢谢!这看起来很有趣。我会尝试一下,需要根据我的知识添加类似的东西。
【解决方案3】:

我看到我们已经有了专家的答案,但只是为了后代的另一种方法。

>>> 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,000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 2021-07-05
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    相关资源
    最近更新 更多