Python Forum

Full Version: Get rows with same value from dataframe of particular columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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()