Skip to content

Instantly share code, notes, and snippets.

@yinleon
Last active March 9, 2023 16:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yinleon/a06f4ae1180fe7d5d3ba288416b666e8 to your computer and use it in GitHub Desktop.
Save yinleon/a06f4ae1180fe7d5d3ba288416b666e8 to your computer and use it in GitHub Desktop.
Perform both a normalized and regular value_counts on a columns (`col`) in a dataframe (`df`).
def value_counts(df: pd.DataFrame,
col: str,
*args, **kwargs) -> pd.DataFrame:
"""
For a DataFrame (`df`): display normalized (percentage)
`value_counts(normalize=True)` and regular counts
`value_counts()` for a given `col`.
"""
count = df[col].value_counts(*args, **kwargs).to_frame(name='count')
perc = df[col].value_counts(normalize=True, *args, **kwargs) \
.to_frame(name='percentage')
return pd.concat([count, perc], axis=1)
@yinleon
Copy link
Author

yinleon commented Mar 16, 2021

This is what it looks like when used:
value_counts_example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment