0

I know this question is quite trivial, but this is my first day of using pandas, so please at least post a link to the document which I should read.

Basically, I don't know how to count the number of items of each column. Suppose I have a data frame like this:

df = pandas.DataFrame({ "Grade": [1, 2, 1, 1, 2, 1, 2, 2, 1], "Major": ["Science", "Art", "Engineering", "Science", "Science", "Science", "Science", "Engineering", "Engineering"]}) 

I expect the following result:

Grade Major Number 1 Science 3 1 Engineering 2 1 Art 0 2 Science 2 2 Engineering 1 2 Art 1 

1 Answer 1

2

I think you need groupby with aggregating size:

print (df.groupby(['Grade','Major']).size().reset_index(name='Number')) Grade Major Number 0 1 Engineering 2 1 1 Science 3 2 2 Art 1 3 2 Engineering 1 4 2 Science 2 

If need add missing values per group, add unstack with stack:

print (df.groupby(['Grade','Major']) .size() .unstack(fill_value=0) .stack() .reset_index(name='Number')) Grade Major Number 0 1 Art 0 1 1 Engineering 2 2 1 Science 3 3 2 Art 1 4 2 Engineering 1 5 2 Science 2 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.