【问题标题】:Filter 2 choices in a column在列中过滤 2 个选项
【发布时间】:2021-11-22 02:57:48
【问题描述】:

谁能告诉我在一个列中过滤 2 个或多个选项的脚本?

例如:

A  B  C  D  E  F   G
1  x  x  x  x  x  AAA
3  x  x  x  x  x  BBB
4  x  x  x  x  x  AAA
1  x  x  x  x  x  CCC
4  x  x  x  x  x  CCC
5  x  x  x  x  x  AAA

我想一次性过滤“AAA”和“BBB”。我试过了:

import pandas as pd 
import numpy as np 
import openpyxl 
from numpy.random import choice

df = pd.read_excel('filepath', sheet_name = 'Sheet1')

df_sample = df.loc[df['G'].str.contains("AAA", 'BBB")]

但它只返回带有“AAA”的G列,但“BBB”不在。

请指导我如何做到这一点。

非常感谢!

【问题讨论】:

    标签: python pandas numpy filter


    【解决方案1】:

    您可以将contains| 分隔符一起使用:

    df[df.G.str.contains("AAA|BBB")]
    

    【讨论】:

      【解决方案2】:

      您将两个参数传递给 contains 函数,来自 documentation

      Series.str.contains(pat, case=True, flags=0, na=None, regex=True)

      你的函数相当于

      df['G'].str.contains(pat="AAA", case="BBB")

      字符串"BBB"在python中被视为True,所以你的代码相当于-

      df['G'].str.contains(pat="AAA", case=True)

      这就是为什么您只获得"AAA" 的结果以获得正确的解决方案,您可以遵循@Nathan Furnal 的解决方案

      df[df.G.str.contains("AAA|BBB")]
      

      【讨论】:

        【解决方案3】:

        您可以使用isincontains,但请记住:

        • isin 检查列中的每个值是否包含在任意值列表中。

        • isin 按列工作,适用于所有数据类型。

        • contains 检查列中的每个值是否包含任意值。

        • contains 按元素工作,仅在处理字符串(或可以表示为字符串的值)时才有意义。


        这是使用isin 的方法:

        choices_to_keep = ["AAA", 'BBB"]
        
        filtered_df = df.G.isin(choices_to_keep)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-02
          • 2014-12-20
          • 1970-01-01
          • 2022-09-27
          • 2017-11-14
          • 1970-01-01
          • 1970-01-01
          • 2021-04-17
          相关资源
          最近更新 更多