-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

user1955215
  • 733
  • 2
  • 11
  • 31
  • 1
    Can you please paste the dataframe into the question? – U13-Forward Aug 20 '21 at 02: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](https://stackoverflow.com/q/20109391/15497888). – Henry Ecker Aug 20 '21 at 02: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? – user1955215 Aug 20 '21 at 02:41

1 Answers1

1

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

Randy
  • 14,349
  • 2
  • 36
  • 42
  • Thanks, This does answer the question and gives the expected result. What would be pivot_table version of the solution? – user1955215 Aug 20 '21 at 02:36
  • @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. – Trenton McKinney Aug 20 '21 at 02:39
  • @TrentonMcKinney, Thanks for the clarification regarding "you cant have the same column value". – user1955215 Aug 20 '21 at 02:44