| import matplotlib.mlab as mlab |
| import matplotlib.pyplot as plt |
| from datetime import datetime |
| from functools import reduce |
| import pandas as pd |
| import numpy as np |
| import os |
| import math |
| import sys |
| import pickle |
| from datetime import datetime |
| from IPython.display import display |
|
|
| |
| def crosstab_dic(dic, var1, var2, rows): |
| for name, df in dic.items(): |
| df[var1] = df[var1].fillna(-1) |
| |
|
|
| ct = pd.crosstab(df[var1], df[var2], dropna=False, margins=True) |
| |
| |
| if len(ct) > rows * 2 + 2: |
| print(f"{name}: first {rows} and last {rows} rows") |
| display(ct.iloc[np.r_[0:rows, -rows:0]]) |
| else: |
| print(f"{name}: all rows") |
| display(ct) |
|
|
| |
| def cdf(raw_df, obs_col, val_cols,x_label,x_upper,x_lower = 0): |
| for val_col in val_cols: |
| df = raw_df[[obs_col, val_col]] |
| df = df.loc[df[val_col].notnull()] |
| assert len(raw_df[obs_col]) == len(raw_df[obs_col].unique()) |
| df = df.sort_values(val_col).reset_index(drop=True) |
| df = df.reset_index() |
| df["Perc"] = df["index"] / len(df) |
| plt.plot(df[val_col], df["Perc"]) |
| tot = len(df) |
| sub = len(df.loc[(df[val_col]<x_upper)&(df[val_col]>x_lower)]) |
| print(f"frac of {val_col}: {sub/tot}") |
|
|
| plt.xlabel(x_label) |
| plt.xlim(x_lower, x_upper) |
| plt.legend(val_cols) |
| plt.show() |
|
|
| |
| def varXtime(raw_df,var, max_yval ,time_var , remove_max = False, label_freq = 3): |
| df = raw_df.groupby(by=[time_var,'AppCode'],as_index = False)[var].sum() |
| |
| df = df.groupby([time_var]).describe().reset_index() |
| df.columns = [''.join(col).strip().replace(var,"") for col in df.columns.values] |
| days = list(df[time_var].unique()) |
| print(f"Graph over {len(days)} days") |
|
|
| count_df = df[[time_var,"count"]] |
| dist_df = df.drop(columns = ["count",'std']) |
| if remove_max == True: |
| dist_df = df.drop(columns=["max"]) |
|
|
| |
| for metric,df in {var:dist_df,"Count":count_df}.items(): |
|
|
| plt.xlabel(time_var,) |
| plt.ylabel(metric) |
|
|
| for col in df.columns: |
| if col == time_var: |
| continue |
| plt.plot(df[time_var],df[col]) |
| labels_dt = list(df[time_var].unique())[::label_freq] |
| labels = [x.strftime("%Y-%m-%d") for x in labels_dt] |
| |
| plt.xticks(labels_dt,labels, rotation=90 ) |
|
|
| if metric == var: |
| plt.ylim(df['min'].min(), max_yval) |
|
|
| plt.legend() |
| plt.show() |
|
|
| |
| def varsXtime(df:pd.DataFrame, vars: list, date_var: str): |
| for var in vars: |
| plt.plot(df[date_var], df[var]) |
| labels_dt = list(df[date_var].unique())[::2] |
| labels = [x.strftime("%Y-%m-%d") for x in labels_dt] |
| plt.xticks(labels_dt, labels, rotation=90) |
| plt.legend() |
| plt.show() |
|
|
|
|