1

I am trying to create a pivot table where I can see the row percentage of each value. This is, imagine I have Index = 'gender' with gender being {Male, Female, Other} and in the column side, I have the response to "Do you have children?", being the response 0 for No and 1 for Yes.

I want to do a table that not not only counts the number of people from each gender that have and have not children, but also the percentage of each of these values.

I have tried:

`pivot1 = pd.pivot_table(df, index='gender', columns=['children'], aggfunc='size')
pivot1.columns = pivot1.columns.ravel()
pivot1['% of Total'] = (df.children / df.children.sum() * 100)
pivot1.loc['total', :] = pivot1.sum().values
pivot1`

But the percentage is not attributed by 0 and 1 of the 'children' column:

enter image description here

Extra: Is there also a way of doing pivot tables with multiple columns but without the multiple indexing?

baldr
  • 2,891
  • 11
  • 43
  • 61
  • Maybe you want to add a complete example with data and expected outcome. That makes helping easier. In the meantime look at https://stackoverflow.com/questions/59840968/transform-pandas-groupby-result-with-subtotals-to-relative-values, that might fit your bill. – divingTobi Oct 04 '20 at 09:35

0 Answers0