|
|
|
import pandas as pd |
|
import numpy as np |
|
import zipfile |
|
|
|
|
|
pd.set_option("mode.copy_on_write", True) |
|
|
|
|
|
|
|
z = zipfile.ZipFile(".01_Data/01_Raw/raw_mortality.zip") |
|
fips = pd.read_csv(".01_Data/01_Raw/county_fips.csv") |
|
abbreviations = pd.read_csv(".01_Data/01_Raw/state_abbreviations.csv") |
|
|
|
|
|
|
|
file_list = sorted([f for f in z.namelist() if f.startswith("Underlying")]) |
|
|
|
|
|
|
|
|
|
df_list = [] |
|
for file in file_list: |
|
|
|
df_temp = pd.read_csv(z.open(file), sep="\t") |
|
|
|
|
|
df_temp.drop(columns=["Notes"], inplace=True) |
|
df_temp.dropna(subset=["County"], inplace=True) |
|
|
|
|
|
df_list.append(df_temp) |
|
|
|
|
|
|
|
df = pd.concat(df_list, ignore_index=True) |
|
|
|
|
|
|
|
df2 = df.copy() |
|
|
|
|
|
df2["County Code"] = df2["County Code"].astype(int).astype(str).str.zfill(5) |
|
|
|
|
|
fips["countyfips"] = fips["countyfips"].astype(str).str.zfill(5) |
|
|
|
|
|
df2["Year"] = df2["Year"].astype(int) |
|
|
|
|
|
df2["Deaths"] = df2["Deaths"].replace("Missing", np.nan) |
|
df2["Deaths"] = ( |
|
df2["Deaths"].astype(float).astype("Int64") |
|
) |
|
|
|
|
|
|
|
|
|
required_causes = [ |
|
"Drug poisonings (overdose) Unintentional (X40-X44)", |
|
"All other drug-induced causes", |
|
"Drug poisonings (overdose) Homicide (X85)", |
|
"Drug poisonings (overdose) Suicide (X60-X64)", |
|
"Drug poisonings (overdose) Undetermined (Y10-Y14)", |
|
] |
|
|
|
|
|
|
|
df3 = df2[df2["Drug/Alcohol Induced Cause"].isin(required_causes)] |
|
|
|
|
|
df3.drop(columns=["Year Code", "Drug/Alcohol Induced Cause Code"], inplace=True) |
|
|
|
|
|
df3.rename( |
|
columns={"Drug/Alcohol Induced Cause": "Cause", "County Code": "County_Code"}, |
|
inplace=True, |
|
) |
|
|
|
|
|
|
|
df4 = pd.merge( |
|
df3, |
|
fips, |
|
how="left", |
|
left_on="County_Code", |
|
right_on="countyfips", |
|
validate="m:1", |
|
indicator=True, |
|
) |
|
|
|
|
|
|
|
|
|
df5 = df4[["BUYER_STATE", "BUYER_COUNTY", "County_Code", "Year", "Cause", "Deaths"]] |
|
|
|
|
|
df5 = df5.rename(columns={"BUYER_COUNTY": "County", "BUYER_STATE": "State_Code"}) |
|
|
|
abbreviations = abbreviations.rename( |
|
columns={ |
|
"state": "State", |
|
"code": "State_Code", |
|
} |
|
) |
|
|
|
|
|
df6 = pd.merge( |
|
df5, |
|
abbreviations[["State", "State_Code"]], |
|
how="left", |
|
on="State_Code", |
|
validate="m:1", |
|
) |
|
|
|
|
|
df6 = df6[["State", "State_Code", "County", "County_Code", "Year", "Cause", "Deaths"]] |
|
|
|
|
|
|
|
df6.to_parquet(".01_Data/02_Processed/02_Mortality.parquet", index=False) |
|
|