Skip to content

Instantly share code, notes, and snippets.

@ryanorsinger
Created January 31, 2023 19:34
Show Gist options
  • Save ryanorsinger/3a83045c9ddcba9cbefbbda70a6e49cf to your computer and use it in GitHub Desktop.
Save ryanorsinger/3a83045c9ddcba9cbefbbda70a6e49cf to your computer and use it in GitHub Desktop.
Groupby Column Rename to Have Name and Percentage (or other Aggregate Function)
# Say we have a number of records per year
# And we need to get the percentage breakdown/makeup of a category for each year
# If we leave the column name as "SomeCategory", but it shows a percent, then we need to rename in order to keep the category's name
x = pd.DataFrame(df.groupby("year").SomeCategory.value_counts(normalize=True).round(2))
x.columns = ["percentage"]
x.reset_index()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment