简体   繁体   English

Pandas:对多列进行布尔索引

[英]Pandas : Boolean indexing on multiple columns

I have a data frame as below. 我有如下数据框。

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

I want to do boolean indexing to filter out columns which have either x or y. 我想做布尔索引来过滤出具有x或y的列。 This i am doing as 这是我做的

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

But i have over 50 columns in which i need to check and checking each columns seems not very pythonic. 但是我有超过50列需要检查,并且检查每列似乎不是很pythonic。 I tried 我试过了

In [30]: df[df[['a','b']].isin(['x','y'])]

But the output is not what i expect, i get the below 但是输出不是我期望的,我得到以下

Out[30]: 
     a    b    c
0    x    y  NaN
1    x  NaN  NaN
2  NaN  NaN  NaN
3  NaN    y  NaN

I can drop rows which are all NaN but the values are missing in the rest. 我可以删除全部为NaN的行,但其余的行中缺少这些值。

For example in row-0 columns-c is NaN but i need that value. 例如,在第0行中,c是NaN,但我需要该值。

Any suggestions how to do this ? 有什么建议怎么做?

You can compare your df with 'x' and 'y' and then do a logical or to find rows with either 'x' or 'y'. 您可以将df与“ x”和“ y”进行比较,然后进行逻辑运算或查找具有“ x”或“ y”的行。 Then use the boolean array as index to select those rows. 然后使用布尔数组作为索引来选择那些行。

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

This works: 这有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM