【问题标题】:How do I get unique values in a Pandas DataFrame that match criteria?如何在 Pandas DataFrame 中获取符合条件的唯一值?
【发布时间】:2021-08-30 20:00:53
【问题描述】:

假设我有以下 DataFrame:

df_amazon = pd.DataFrame ({
    'order_no':[1, 2, 3],
    'category':['Books', 'Toys', 'Books'],
    'seller':['Amazon.com', 'AZ Toys', 'amazon'] })

如果卖家列中与亚马逊相关,我想获取所有唯一值。

在 SQL 中,有一个 LIKE 关键字。例如:

SELECT seller FROM df_amazon WHERE LOWER(seller) LIKE 'amazon%' 

上面的代码会返回所有卖家列中小写字母以“amazon”开头的记录。

Pandas 中有类似的东西吗?

我尝试了以下方法:

df_amazon.loc[df_amazon.seller.str.contains('amazon')]

但这在第三行严格匹配,第一行省略了“Amazon.com”。

然后我尝试了以下方法:

df_amazon.loc[df_amazon.seller.str.lower().contains('amazon')]

但这会返回错误:AttributeError: 'Series' object has no attribute 'contains'

我想快速获取卖家为亚马逊的所有唯一值。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    Series.str.contains 中的case=False 参数与Series.unique 一起使用:

    df_amazon.loc[df_amazon.seller.str.contains('amazon', case=False), 'seller'].unique()
    

    你的第二个解决方案被另一个str修改:

    df_amazon.loc[df_amazon.seller.str.lower().str.contains('amazon'), 'seller'].unique()
    

    【讨论】:

    • 可能在loc的列部分中输入seller,只选择卖家列;它应该符合 OP 的要求
    • 如果我想获取所有唯一值,我会使用什么,因为当我将该逻辑放入 df_amazon.seller.unique() 时出现错误:df_amazon.seller.unique( df_amazon.loc[df_amazon.seller.str.contains('amazon', case = False)] ) 返回 TypeError: unique( ) 接受 1 个位置参数,但给出了 2 个
    【解决方案2】:

    你必须再多一个.str:

    df_amazon.loc[df_amazon.seller.str.lower().str.contains('amazon')]
    

    或使用case=False:

    df_amazon.loc[df_amazon.seller.str.contains('amazon', case=False)]
    

    或指定标志:

    import re
    df_amazon.loc[df_amazon.seller.str.lower().str.contains('amazon',  flags=re.IGNORECASE)]
    

    【讨论】:

      猜你喜欢
      • 2018-03-14
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-11
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多