Home > Software design >  Pandas count column a if column b condition
Pandas count column a if column b condition

Time:11-30

I have a dataframe with two columns as shown below.

location   date
paris       6    
paris       4    
rome        3    
paris       5    
paris       6    
rome        6    
paris       4

Now I would like to have counted the different areas in column a, if column b is equal to 6. So the desired result would be:

Paris 2

Rome 1

I am a total noob tbh, the basic idea would be: If column "date" is 6, count the values in column location.

Thx for any help.

CodePudding user response:

It would be something like:

df[df['date']==6].groupby('location').count()

The df[df['date']==6] part, filters your DataFrame to only include rows with date values equal to 6. groupby('location') group filtered DataFrame by location value and count() counts the number of rows in groups.

CodePudding user response:

Let's say your dataframe is df:

df[df['date'] == 6]['location'].value_counts()

Will give you your desired result:

paris    2
rome     1
Name: location, dtype: int64
  • Related