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
  Merging rows and adding columns based on matching index pythonnewbie78 3 750 Dec-24-2023, 11:51 AM
Last Post: Pedroski55
  How to add columns to polars dataframe sayyedkamran 1 1,689 Nov-03-2023, 03:01 PM
Last Post: gulshan212
  concat 3 columns of dataframe to one column flash77 2 778 Oct-03-2023, 09:29 PM
Last Post: flash77
  Pandas Dataframe Filtering based on rows mvdlm 0 1,396 Apr-02-2022, 06:39 PM
Last Post: mvdlm
  Convert several columns to int in dataframe Krayna 2 2,363 May-21-2021, 08:55 AM
Last Post: Krayna
  Outputs "NaN" after "DataFrame columns" function? epsilon 7 3,572 Jan-27-2021, 10:59 AM
Last Post: epsilon
  change dataframe header with 2 rows tonycat 2 1,966 Oct-29-2020, 01:41 AM
Last Post: tonycat
  Adapting a dataframe to the some of columns flyway 2 2,032 Aug-12-2020, 07:21 AM
Last Post: flyway
  Difference of two columns in Pandas dataframe zinho 2 3,314 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 2,079 Mar-18-2020, 06:07 AM
Last Post: mani

Forum Jump:

User Panel Messages

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