简体   繁体   中英

Show zero values for a column after performing conditional groupby count in pandas

I've a dataframe as mentioned below:

[1]:https://i.stack.imgur.com/nDMa5.png

I'm using the following code to get the count of resolved for all the items in column A :

resolved = df[df['B']== 'resolved'].groupby('A', as_index=False)['B'].size()

and similarly for unresolved :

unresolved = df[df['B']== 'unresolved'].groupby('A', as_index=False)['B'].size()

For unresolved , SRVCAM-AM BI-Data doesn't have unresolved value in column B . So, the resulting dataframe will not have it

The result obtained for unresolved is as below:

work_queue count SRVCAM-AM BI-Reports Admin 1

but I want the result as follows:

work_queue count SRVCAM-AM BI-Reports Admin 1 SRVCAM-AM BI-Data 0

You can compare column B and aggregate sum - True s are processes like 1 s:

resolved = (df['B'] == 'resolved').groupby(df['A'], as_index=False).sum().astype(int)

If want all columns by B use crosstab :

resolved = pd.crosstab(df['A'], df['B'])

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