2

I am trying to take the count of 'STAGE' occurrence based on project, I used np.size as aggfunc but it return number of occurrence including the project, My count value become double if expected count is 3 means it return 6

enter image description here

I used the below code

df = pd.pivot_table(data_frame, index=['Project'],columns=['Stage'], aggfunc=np.size, fill_value=0)

1 Answer 1

3

You need aggregate function len:

print (data_frame)
  Project Stage
0      an    ip
1     cfc    pe
2      an    ip
3      ap    pe
4     cfc    pe
5      an    ip
6     cfc    ip

df = pd.pivot_table(data_frame, 
                    index='Project',
                    columns='Stage', 
                    aggfunc=len, 
                    fill_value=0)
print (df)
Stage    ip  pe
Project        
an        3   0
ap        0   1
cfc       1   2

Another solution with size:

df = pd.pivot_table(data_frame, 
                    index='Project',
                    columns='Stage', 
                    aggfunc='size', 
                    fill_value=0)
print (df)
Stage    ip  pe
Project        
an        3   0
ap        0   1
cfc       1   2

EDIT by comment:

import matplotlib.pyplot as plt
#all code

df.plot.bar()
plt.show()

graph

Sign up to request clarification or add additional context in comments.

1 Comment

Can we able to convert this pivot table into bar chart directly, Like project as in x - axis and stage as stacked bar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.