Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:多列上的布尔索引_Python_Pandas - Fatal编程技术网

Python 熊猫:多列上的布尔索引

Python 熊猫:多列上的布尔索引,python,pandas,Python,Pandas,我有一个数据框,如下所示 In [23]: data2 = [{'a': 'x', 'b': 'y','c':'q'}, {'a': 'x', 'b': 'p', 'c': 'q'}, {'a':'p', 'b':'q'},{'a':'q', 'b':'y','c':'q'}] In [26]: df = pd.DataFrame(data2) In [27]: df Out[27]: a b c 0 x y q 1 x p q 2 p q NaN 3

我有一个数据框,如下所示

In [23]: data2 = [{'a': 'x', 'b': 'y','c':'q'}, {'a': 'x', 'b': 'p', 'c': 'q'}, {'a':'p', 'b':'q'},{'a':'q', 'b':'y','c':'q'}]
In [26]: df = pd.DataFrame(data2)
In [27]: df
Out[27]: 
   a  b    c
0  x  y    q
1  x  p    q
2  p  q  NaN
3  q  y    q
我想做布尔索引来过滤掉包含x或y的列。这是我正在做的

In [29]: df[df['a'].isin(['x','y']) | (df['b'].isin(['x','y']))]
Out[29]: 
   a  b  c
0  x  y  q
1  x  p  q
3  q  y  q
但我有50多列,我需要检查,检查每一列似乎不是很pythonic。 我试过了

In [30]: df[df[['a','b']].isin(['x','y'])]
但是输出不是我所期望的,我得到了下面的结果

Out[30]: 
     a    b    c
0    x    y  NaN
1    x  NaN  NaN
2  NaN  NaN  NaN
3  NaN    y  NaN
我可以删除所有为NaN的行,但其余的行中缺少值

例如,在第0行的列中,c是NaN,但我需要该值


有什么建议吗?

您可以将df与“x”和“y”进行比较,然后进行逻辑or运算,以查找带有“x”或“y”的行。然后使用布尔数组作为索引来选择这些行

df.loc[(df.eq('x') | df.eq('y')).any(1)]
Out[68]: 
   a  b  c
0  x  y  q
1  x  p  q
3  q  y  q

您可以将df与“x”和“y”进行比较,然后执行逻辑or以查找具有“x”或“y”的行。然后使用布尔数组作为索引来选择这些行

df.loc[(df.eq('x') | df.eq('y')).any(1)]
Out[68]: 
   a  b  c
0  x  y  q
1  x  p  q
3  q  y  q
这项工作:

df.loc[df.apply(lambda x: 'x' in list(x) or 'y' in list(x), axis=1)]

   a  b  c
0  x  y  q
1  x  p  q
3  q  y  q
这项工作:

df.loc[df.apply(lambda x: 'x' in list(x) or 'y' in list(x), axis=1)]

   a  b  c
0  x  y  q
1  x  p  q
3  q  y  q