【问题标题】:Get a subset of a dataframe where columns must contain substring (if not, ignore those rows)获取数据框的子集,其中列必须包含子字符串(如果不是,则忽略这些行)
【发布时间】:2021-08-28 04:34:53
【问题描述】:

有很多类似的问题,但没有人问这个具体的问题,我不知道如何解决。

假设我有一个如下所示的数据框df,并假设每一列都可以有其他子字符串(尽管,下面显示的子字符串对于每行一列都是唯一的,例如,如果一列有'Coin ' 在其中,该行中没有其他列可以包含子字符串 'Coin')。

此示例显示了整个字符串,但假设其中包含“Coin”的行实际上可能是“Coin (quarters)”,因此它必须搜索子字符串“Coin”而不假设“Coin”是整个字符串字符串。

>>> df

   1       2       3       4       cap
0  Coin    Bill    Charge          72
1  Coin                            13
2  Charge  Coin                     1
3  Bill    Other   Coin    Charge  57
4  Charge  Bill                    11
5  Coin    Charge                   8
6  Other   Bill    Charge   Coin   99
7  Charge                          45 
8  Charge  Coin                    15
9  Bill    Other   Coin            71

当且仅当列包含“Coin”和“Charge”但不包含其他唯一子字符串时,我想要做的是选择行。本质上,当且仅当一列包含“Coin”且一列包含“Charge”且其余列不包含“Bill”或“Other”或者它们具有空字符串。

因此,在上面的示例中,生成的数据框将是 df 的子集:

>>> df_res

   1       2       3       4       cap
2  Charge  Coin                     1
5  Coin    Charge                   8
8  Charge  Coin                    15

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    试试:

    x = df[
        df.apply(
            lambda x: "Coin" in (v := x.values)
            and "Charge" in v
            and "Bill" not in v
            and "Other" not in v,
            axis=1,
        )
    ]
    print(x)
    

    打印:

            1       2 3 4  cap
    2  Charge    Coin        1
    5    Coin  Charge        8
    8  Charge    Coin       15
    

    编辑:搜索子字符串:

    x = df[
        df.apply(
            lambda x: any("Coin" in i for i in x if isinstance(i, str))
            and any("Charge" in i for i in x if isinstance(i, str))
            and not any("Bill" in i for i in x if isinstance(i, str))
            and not any("Other" in i for i in x if isinstance(i, str)),
            axis=1,
        )
    ]
    print(x)
    

    打印:

            1               2 3 4  cap
    2  Charge  Coin(quarters)        1
    5    Coin          Charge        8
    8  Charge            Coin       15
    

    【讨论】:

    • df.apply 超级慢:/
    • @JoranBeasley 毕竟,这些值是字符串。 Pandas 在这里帮不上什么忙,它适用于数字处理。
    • 一个 str.join 和一个 str.search 可能会更快......虽然最终这应该可以工作......
    • 这很好,但如果“Coin”或“Charge”是较大字符串中的子字符串,则它不起作用。只有当他们独自一人时。
    猜你喜欢
    • 1970-01-01
    • 2020-03-24
    • 2017-10-19
    • 2017-08-18
    • 2017-02-23
    • 2021-09-16
    • 2022-01-20
    • 2019-03-24
    • 2019-10-07
    相关资源
    最近更新 更多