简体   繁体   中英

How to pandas groupby specific value in a column?

I have a dataframe with multiple columns using with added a new column for age intervals.

# Create Age Intervals
bins = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
df['age_intervals'] = pd.cut(df['age'],bins)

Now, I've another column named no_show that states whether a person shows up for the appointment or not using values 0 or 1. By using the below code, I'm able to groupby the data based on age_intervals .

df[['no_show','age_intervals']].groupby('age_intervals').count()

Output: 
age_intervals   no_show
  (0, 5]        8192
 (5, 10]        7017
(10, 15]        5719
(15, 20]        7379
(20, 25]        6750

But how can I group the no_show data based on its values 0 and 1. For example, in the age interval (0,5], out of 8192, 3291 are 0 and 4901 are 1 for no_show and so on.

An easy way would be to group on both columns and use size() which returns a Series:

df.groupby(['age_intervals', 'no_show']).size()

This will return a Series with divided values depending on both the age_intervals column and the no_show column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM