如何按布尔值过滤?

时间:2020-01-29 19:59:19

标签: python pandas dataframe

我提取了一系列布尔值,我想在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。

2 个答案:

答案 0 :(得分:1)

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

jq: error (at <stdin>:2): null (null) has no keys
jq: error (at <stdin>:3): null (null) has no keys
jq: error (at <stdin>:4): null (null) has no keys
jq: error (at <stdin>:5): null (null) has no keys

组合的过滤器将返回:

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

答案 1 :(得分:1)

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

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

使用np.where

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

OR

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