Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe Find Rows Where all Columns Equal

Tags:

python

pandas

I have a dataframe that has characters in it - I want a boolean result by row that tells me if all columns for that row have the same value.

For example, I have

df = [  a   b   c   d  0  'C'   'C'   'C'   'C'   1  'C'   'C'   'A'   'A'  2  'A'   'A'   'A'   'A' ] 

and I want the result to be

0  True  1  False  2  True 

I've tried .all but it seems I can only check if all are equal to one letter. The only other way I can think of doing it is by doing a unique on each row and see if that equals 1? Thanks in advance.

like image 765
Lisa L Avatar asked Mar 28 '14 00:03

Lisa L


People also ask

How do you check if all values in a row are the same Pandas?

Pandas DataFrame has methods all() and any() to check whether all or any of the elements across an axis(i.e., row-wise or column-wise) is True.

How do I see specific rows in Pandas?

You may need to see the value of a specific row to identify the root cause of the errors. You can use the df. loc[[2]] to print a specific row of a pandas dataframe.


1 Answers

I think the cleanest way is to check all columns against the first column using eq:

In [11]: df Out[11]:     a  b  c  d 0  C  C  C  C 1  C  C  A  A 2  A  A  A  A  In [12]: df.iloc[:, 0] Out[12]:  0    C 1    C 2    A Name: a, dtype: object  In [13]: df.eq(df.iloc[:, 0], axis=0) Out[13]:        a     b      c      d 0  True  True   True   True 1  True  True  False  False 2  True  True   True   True 

Now you can use all (if they are all equal to the first item, they are all equal):

In [14]: df.eq(df.iloc[:, 0], axis=0).all(1) Out[14]:  0     True 1    False 2     True dtype: bool 
like image 115
Andy Hayden Avatar answered Sep 16 '22 14:09

Andy Hayden