-
-
Save Syrus/6e5269a81f9ac2dbe6b5d935b4526f7e to your computer and use it in GitHub Desktop.
Analyze data frames that contain mainly categorical (string) data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pandas as pd | |
| def describe_population(df: pd.DataFrame) -> pd.DataFrame: | |
| """ | |
| Report the populated and uniqueness counts for each column of the input. | |
| """ | |
| N = len(df) | |
| dtypes = df.dtypes | |
| distincts = df.nunique() | |
| nas = df.isnull().sum() | |
| pop = N - nas | |
| out = pd.DataFrame() | |
| out['dtype'] = dtypes | |
| out['na'] = nas | |
| out['populated'] = pop | |
| out['distinct'] = distincts | |
| tops = [] | |
| freqs = [] | |
| for c in df.columns: | |
| temp = df[c].value_counts() | |
| if len(temp) > 0: | |
| tops.append(temp.index[0]) | |
| freqs.append(temp.values[0]) | |
| else: | |
| tops.append(np.nan) | |
| freqs.append(0) | |
| out['top'] = tops | |
| out['freq'] = freqs | |
| out['pop/N'] = 100 * pop / N | |
| out['dist/pop'] = 100 * distincts / pop | |
| out['freq/N'] = [float(n)/N for n in freqs] | |
| out.columns.name = "N = {:,}".format(N) | |
| return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment