Home > Blockchain >  In Pandas, how do I change the name of a cell after using .sum()?
In Pandas, how do I change the name of a cell after using .sum()?

Time:03-25

I am creating some tables for describing survey respondent demographics. I have created a table that lists out how many of each demographic are in the data:

g = df['Q04 - Gender'].value_counts().reset_index()
g= g.rename(columns={'index': 'gender', 'Q04 - Gender':'Total_Count'})
g.loc["Total"]=g.sum()
g

This creates a table with a row at the bottom for "Total", but a value in that row that is all of the preceding names concatenated:

MaleFemalePrefer not to sayNon-binary / third ...

How do I make this say "Total" or just be blank?

I have tried searching for ways to do this but all I can find are ways to change the names of columns and rows. In this case the row name is correct however, but it is the cell that is showing an unhelpful name.

CodePudding user response:

rename and reset_index() after calculating your total:

g = df['Q04 - Gender'].value_counts()
g.loc["Total"] = g.sum()
g = g.reset_index().rename(columns={'index': 'gender', 'Q04 - Gender':'Total_Count'})
  • Related