-1

I am having a DataFrame (28 rows from the Titanic passenger list) which has a column "Sex" consisting of two values, "Male", "Female". I want to get the count of Males/Females

The output should show "Sex" as Row labels(index) and the count (of Male/Female) in the second column

df.pivot_table(index ="Sex", values ="Sex", aggfunc='count')

This returns a "ValueError: Grouper for 'Sex' not 1-dimensional" error.

Please guide

3
  • 1
    Can you please paste the dataframe into the question? Commented Aug 20, 2021 at 2:29
  • If you need assistance formatting a small sample of your DataFrame as a copyable piece of code for SO see How to make good reproducible pandas examples. Commented Aug 20, 2021 at 2:31
  • df.pivot_table(index ="Sex",values="PassengerId", aggfunc='count') - This works and gives the result(i.e. when the index and values are different fields. Can it not be done with only the "Sex" column? Commented Aug 20, 2021 at 2:41

1 Answer 1

1

It's just df['Sex'].value_counts()

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

3 Comments

Thanks, This does answer the question and gives the expected result. What would be pivot_table version of the solution?
@user1955215 there isn't one. Look at df.pivot_table(columns="sex", aggfunc='count') and then look at df.pivot_table(index="sex", aggfunc='count'). You'll see that you can't have the same column value for both index and values.
@TrentonMcKinney, Thanks for the clarification regarding "you cant have the same column value".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.