Download 17/replication_package/code/lib/utilities/codebook.py from chuxuan/REPRO-Bench: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/datasets/chuxuan/REPRO-Bench/resolve/main/17/replication_package/code/lib/utilities/codebook.py
- Command line
-
hf download hf://datasets/chuxuan/REPRO-Bench/17/replication_package/code/lib/utilities/codebook.py
-
curl -L -o codebook.py https://huggingface.co/datasets/chuxuan/REPRO-Bench/resolve/main/17/replication_package/code/lib/utilities/codebook.py
6.63 kB
| import pandas as pd | |
| import numpy as np | |
| import os | |
| import sys | |
| from lib.experiment_specs import study_config | |
| from lib.utilities import serialize | |
| main_codebook_path = os.path.join("data","external","intermediate","CompressedCodebook.csv") | |
| final_codebook_path = os.path.join("data","external","final","CodebookFinal.csv") | |
| manual_specs_path = os.path.join("lib","experiment_specs","ManualCodebookSpecs.xlsx") | |
| value_label_path = os.path.join("lib","experiment_specs","value_labels.yaml") | |
| phase_encode_options = ["Survey","OldPhase","NewPhase"] | |
| codebook_vars = ["VariableName","VariableLabel","RawVariableName","DataType","PrefixEncoding","ValueLabels"] | |
| """ | |
| Function which saves over previous codebook and creates new codebook starting with master_codebook. It only reads the codebook sheet you input. | |
| """ | |
| def initialize_main_codebook(): | |
| cb = pd.read_excel(manual_specs_path,sheet_name = "User") | |
| new_cols = [x for x in codebook_vars if x not in cb.columns] | |
| for new_col in new_cols: | |
| cb[new_col] = "" | |
| cb.to_csv(main_codebook_path, index = False) | |
| """ | |
| Function which adds all non-empty values in the manual_specs to the codebook on disk. This is a substitute for initialize codebook, when we don't | |
| want to reread all the survey names | |
| """ | |
| def update_master_specs(): | |
| #try: | |
| cb = pd.read_csv(main_codebook_path, index_col = "VariableName").to_dict(orient = 'index') | |
| ms = pd.read_excel(manual_specs_path, index_col = "VariableName", sheet_name= "User").to_dict(orient = 'index') | |
| for col,chars in ms.items(): | |
| #if col not in codebook, add all specs | |
| try: | |
| if col not in cb: | |
| cb[col] = ms[col] | |
| cb[col]["ValueLabels"] = None | |
| #if col in codebook, add all specs that are NOT Empty in the manual specs | |
| else: | |
| for char, val in chars.items(): | |
| #if not ((type(val) == float) and (np.isnan(val))): | |
| cb[col][char] = ms[col][char] | |
| except: | |
| print(f"error updating {col} in codebook") | |
| pd.DataFrame.from_dict(cb, orient='index').to_csv(main_codebook_path, index_label="VariableName") | |
| """ | |
| changes variable names in the dataframe according to all vars in the master codebook for which the raw name is different from the regular name | |
| (this function should only be applied to surveys) | |
| """ | |
| def rename_vars(df): | |
| specs = pd.read_excel(manual_specs_path) | |
| new_vars = specs.loc[(specs["VariableName"] != specs["RawVariableName"]) & | |
| (specs["VariableName"].notnull()) & | |
| (specs["RawVariableName"].notnull())] | |
| var_dic = dict(zip(new_vars["RawVariableName"], new_vars["VariableName"])) | |
| for var in df.columns.values: | |
| if var in var_dic.keys(): | |
| df = df.rename(columns = {var : var_dic[var]}) | |
| return df | |
| """ | |
| Adds raw variable names and labels form surveys to codebook | |
| """ | |
| def add_vardic_to_codebook(vardic): | |
| cb = pd.read_csv(main_codebook_path,index_col = "VariableName").to_dict(orient = 'index') | |
| for col, chars in vardic.items(): | |
| # If var is already specified in code book (i.e. the var is manually specified) | |
| if col in cb: | |
| #Only modify a char if it is empty | |
| for cb_var in ["VariableLabel","DataType","PrefixEncoding"]: | |
| val = cb[col][cb_var] | |
| if type(val) == float and np.isnan(val): | |
| cb[col][cb_var] = vardic[col][cb_var] | |
| # Add the var to the codebook | |
| else: | |
| cb[col] = { | |
| "VariableLabel": chars["VariableLabel"], | |
| "RawVariableName": None, | |
| "DataType": chars["DataType"], | |
| "PrefixEncoding": chars["PrefixEncoding"], | |
| "ValueLabels": None | |
| } | |
| pd.DataFrame.from_dict(cb, orient = 'index').to_csv(main_codebook_path, index_label = "VariableName" ) | |
| """ | |
| Reads in dictionary from value_labels.yaml and populates the ValueLabels column in the master codebook | |
| """ | |
| def add_labels_to_codebook(): | |
| cb = pd.read_csv(main_codebook_path, index_col="VariableName").to_dict(orient='index') | |
| label_dic = serialize.open_yaml(value_label_path) | |
| for label, chars in label_dic.items(): | |
| for variable in chars["VariableList"]: | |
| if variable in cb: | |
| cb[variable]["ValueLabels"] = chars["ValueLabels"] | |
| pd.DataFrame.from_dict(cb, orient = 'index').to_csv(main_codebook_path, index_label = "VariableName") | |
| def create_expanded_codebook(df): | |
| cb_e = df.iloc[0,:].transpose().reset_index() | |
| cb_e.columns = ["VariableName","VariableLabel"] | |
| cb_e.index = cb_e["VariableName"] | |
| cb_e["ValueLabels"] = "" | |
| cb_e = cb_e.drop(columns = "VariableName").to_dict(orient='index') | |
| label_dic = serialize.open_yaml(value_label_path) | |
| for label, chars in label_dic.items(): | |
| for variable in chars["VariableList"]: | |
| for code in [study_config.surveys[x]["Code"] for x in study_config.surveys.keys()]: | |
| full_var = code+"_"+variable | |
| if full_var in cb_e: | |
| cb_e[full_var]["ValueLabels"] = chars["ValueLabels"] | |
| pd.DataFrame.from_dict(cb_e, orient = 'index').to_csv(final_codebook_path, index_label = "VariableName") | |
| """given the treatment phase and the codebook dic, this function inputs a varname and outputs | |
| the varname with a prefix""" | |
| def add_prefix_var(var,phase,codebook_dic,): | |
| start_code = study_config.phases[phase]["StartSurvey"]["Code"] | |
| end_code = study_config.phases[phase]["EndSurvey"]["Code"] | |
| if var in study_config.main_cols+study_config.embedded_main_cols: | |
| return var | |
| elif var not in codebook_dic: | |
| print(f"{var} not in codebook!!") | |
| return start_code + "_" + var | |
| elif codebook_dic[var]["PrefixEncoding"] == "Survey": | |
| "if it's a survey variable, assume that it's phrased as 'in the past three weeks' " | |
| if phase == "Phase1": | |
| "for phase1 the survey vars focus on the 3 weeks BEFORE the baseline(start) survey" | |
| return start_code + "_" + var | |
| else: | |
| "For phase 2 and 3, the survey vars focus on the 3 weeks AFTER the start survey" | |
| return end_code + "_" + var | |
| elif codebook_dic[var]["PrefixEncoding"] == "NewPhase": | |
| "If it's a variable on use in the future, always use the start survey" | |
| return start_code + "_" + var | |
| elif codebook_dic[var]["PrefixEncoding"] == "OldPhase": | |
| """These variables collect use data that are reported in the end survey (i.e. Web Data) """ | |
| return end_code + "_" + var |