Python Forum
Get rows with same value from dataframe of particular columns
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get rows with same value from dataframe of particular columns
#1
I have a dataframe with a lot of columns with binary values.
[Image: TeSfMEynRlxDB2p7iQJhGSCTEW4li2bQ_08up0z1...ixerQ=s170]

Is it possible to count the number of rows that satisfy a condition

ex: the number of rows for Col1 and Col2 that are both 1 is 2

similarly the number of rows for Col1 and Col2 that are 0 and 1 is 1

Is there an easy way to do this rather than looping all over the dataframe?
Reply
#2
import pandas as pd
z = pd.DataFrame({'Col1': [1,0,1,1,0,0,1], 'Col2': [0,1,1,1,0,1,0]})

# The number of rows, where both Col1 and Col2 == 0
((z.Col1==0)&(z.Col2==0)).sum()

# The number of rows, where Col1==0 and Col2 == 1
((z.Col1==0)&(z.Col2==1)).sum()

# The number of rows, where both Col1 and Col2 == 1
((z.Col1==1)&(z.Col2==1)).sum()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  change dataframe header with 2 rows tonycat 2 183 Oct-29-2020, 01:41 AM
Last Post: tonycat
  Adapting a dataframe to the some of columns flyway 2 486 Aug-12-2020, 07:21 AM
Last Post: flyway
  Difference of two columns in Pandas dataframe zinho 2 839 Jun-17-2020, 03:36 PM
Last Post: zinho
  DataFrame: To print a column value which is not null out of 5 columns mani 2 542 Mar-18-2020, 06:07 AM
Last Post: mani
Question Dividing a single column of dataframe into multiple columns based on char length darpInd 2 550 Mar-14-2020, 09:19 AM
Last Post: scidam
  Interate for loop over certain columns in dataframe Finpyth 2 528 Mar-06-2020, 08:34 AM
Last Post: Finpyth
  How to highlight dataframe columns SriRajesh 1 538 Feb-28-2020, 11:02 PM
Last Post: Marbelous
  Does the order of columns in the DataFrame matter? new_to_python 11 1,204 Feb-17-2020, 12:32 AM
Last Post: scidam
  read_csv error and rows/columns missing karlito 9 1,121 Nov-11-2019, 06:48 AM
Last Post: karlito
  Pandas dataframe columns collapsed in Spyder when printing UniKlixX 2 1,221 Nov-04-2019, 07:00 AM
Last Post: UniKlixX

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020