I have a data frame:
Dept_Name | Placed |
---|---|
A | 1 |
B | 0 |
C | 1 |
Where 'Placed' column has a boolean value I want to print the count of rows that have the value '1' in placed grouped by the Dept_Name
Dept_Name | Count(Placed == 1) |
---|---|
A | 3 |
B | 4 |
C | 0 |
CodePudding user response:
As you have a boolean 0/1 a simple sum will work:
out = df.groupby('Dept_Name', as_index=False).sum()
output:
Dept_Name Placed
0 A 5
1 B 0
2 C 2
For a named column:
out = df.groupby('Dept_Name', as_index=False).agg(**{'Count': ('Placed', 'sum')})
output:
Dept_Name Count
0 A 5
1 B 0
2 C 2
CodePudding user response:
If values are 0,1
or True/False
you can aggregate sum
, last for column Count
use Series.reset_index
:
df1 = df.groupby('Dept_Name')['Placed'].sum().reset_index(name='Count')
If test some non boolean values - e.g. count values 100
:
df2 = df['Placed'].eq(100).groupby(df['Dept_Name']).sum().reset_index(name='Count')