【问题标题】:How to filter by boolean?如何按布尔值过滤?
【发布时间】:2020-05-15 09:34:26
【问题描述】:

我提取了一系列布尔值,我想在 Pandas 中从中过滤一个数据框,但它没有返回任何结果。

数据框

  Account   mphone  rphone  BPHONE
0 14999201  3931812 8014059 9992222
1 12980801  4444444 3932929 4279999
2 9999999   3279999 4419999 3938888

这是系列:

df['BPHONE'].str.startswith(tuple(combined_list))

0    False
1     True
2    False
Name: BPHONE, dtype: bool

df['rphone'].str.startswith(tuple(combined_list))

0     True
1    False
2     True
Name: rphone, dtype: bool

现在下面,当我尝试过滤时,我得到空结果:

df[(df['BPHONE'].str.startswith(tuple(combined_list))) & (df['rphone'].str.startswith(tuple(combined_list)))]

    Account mphone  rphone  BPHONE

最后,当我只使用一列时,它似乎是按行而不是按列匹配和过滤。这里有关于如何纠正这个问题的建议吗?

df[(df['BPHONE'].str.startswith(tuple(combined_list)))]

  Account   mphone  rphone  BPHONE
1 12980801  4444444 3932929 4279999

我认为这应该只是沿列轴而不是行轴填充 BPHONE。我怎样才能以这种方式过滤?

想要的输出如下:

Account  mphone rphone   BPHONE
14999201 3931812 8014059 np.nan
12980801 4444444 np.nan  4279999
99999999 3279999 4419999 np.nan

为了解释这一点,rphone 显示 True、False、True,因此只有 True 数字应该显示。在 False 下它不应显示,或显示为 NAN。

【问题讨论】:

  • 你得到的是合法的。看看df['BPHONE'].str.containsdf['rphone'].str.contains 的结果——你看到两个结果都为真的行吗?
  • 布尔掩码对行进行操作。您不会得到任何结果,因为 True False TrueFalse True False 是互斥的。您说您正在尝试对列进行操作,您能否提供您首选输出的示例以制作minimal reproducible example,以便我们更好地了解您的问题?
  • 您希望得到什么?它似乎与您共享的代码的逻辑不同。
  • 我添加了预期的内容。谢谢!

标签: python pandas dataframe


【解决方案1】:

您期望的输出不是过滤结果,而是有条件替换的结果。

condition = df['BPHONE'].str.startswith(tuple(combined_list))

使用np.where

df['BPHONE'] = pd.np.where(condition, df['BPHONE'], pd.np.nan)

df.loc[~condition, 'BPHONE'] = pd.np.nan

【讨论】:

    【解决方案2】:

    您应用的所有过滤器都正常运行:

    df['BPHONE'].str.startswith(tuple(combined_list))   
    0    False
    1     True #Only this row will be retained 
    2    False
    

    组合过滤器将返回:

    df[(df['BPHONE'].str.startswith(tuple(combined_list))) & (df['rphone'].str.startswith(tuple(combined_list)))]
    
        First filter Second filter Combined filter
    0          False          True           False #Not retained
    1           True         False           False #Not retained
    2          False          True           False #Not retained
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2021-05-28
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 2014-05-11
      相关资源
      最近更新 更多