usa_opioid_overdose / 02_Codes /06_master_script.py
revanth7667's picture
updated
6e55cce
raw
history blame
4.67 kB
"""
To impute the missing death data based on the state level mortality.
Saves final dataset as data.parquet
refer to the 05_master_eda.ipynb for EDA and other details like how the data was imputed.
"""
# importing libraries and setting default option
import pandas as pd
import numpy as np
pd.set_option("mode.copy_on_write", True)
# reading the data files
df = pd.read_parquet(".01_Data/02_Processed/02_Mortality.parquet")
population = pd.read_parquet(".01_Data/02_Processed/01_Population.parquet")
# ------------------------------------------
# initial Cleaning
df = df[df["State"] != "AK"] # dropping ALASKA since it is Out of Scope (OOS)
# We will consider only unintentional drug related deaths since other have very few values
df = df[df["Cause"] == "Drug poisonings (overdose) Unintentional (X40-X44)"]
df = (
df.dropna()
) # dropping rows with missing values since they are very few and will be imputed later
# ------------------------------------------
# Merge with population data
combined = pd.merge(
df,
population,
on=["State", "State_Code", "County", "County_Code", "Year"],
how="left",
validate="1:1",
indicator=True,
)
# ------------------------------------------
# Clean the Merged Data
df2 = combined[
[
"State",
"State_Code",
"County",
"County_Code",
"Year",
"Population",
"Deaths",
]
]
# ------------------------------------------
# calculating Mortality Rate (County Level)
df3 = df2.copy()
df3["Mortality_Rate"] = df3["Deaths"] / df3["Population"]
# ------------------------------------------
# Mortality Rate (State Level)
# aggregate at state-cause level
df4 = (
df3.groupby(["State", "Year"])
.agg({"Deaths": "sum", "Population": "sum"})
.reset_index()
)
# clacualting mortality rate
df4["State_Mortality_Rate"] = df4["Deaths"] / df4["Population"]
# ------------------------------------------
# Creating a list of State-Counties from the POPULATION dataset
st_county = population[
["State", "State_Code", "County", "County_Code", "Year"]
].drop_duplicates()
# ------------------------------------------
# Merging State Mortality Rate with State-County list
master = pd.merge(st_county, df4, on=["State", "Year"], how="left", indicator=True)
# dropping NA rows since we have no state level data for them
master = master[master["_merge"] == "both"]
# Cleaning the merged data
master_2 = master[
[
"State",
"State_Code",
"County",
"County_Code",
"Year",
"State_Mortality_Rate",
]
]
# ------------------------------------------
# merge with the county level data
df5 = pd.merge(
master_2,
df3,
on=["State", "State_Code", "County", "County_Code", "Year"],
how="left",
indicator=True,
validate="1:1",
)
# adding a new flag to identify if original data or not
df5["Original"] = df5["_merge"] == "both"
# ------------------------------------------
# Remap with population data to get county population
df6 = pd.merge(
df5,
population[["County_Code", "Year", "Population"]],
on=["County_Code", "Year"],
how="left",
validate="1:1",
indicator="merge2",
)
# ------------------------------------------
def new_death(row):
"""Function to Calcuate the deaths in county using the State Mortality Rate and County Population
if the deaths are missing in the original dataset.
Max value is limited to 9 since we know that it can't be 10 or more"""
if pd.isna(row["Deaths"]):
return min(int(row["Population_y"] * row["State_Mortality_Rate"]), 9)
else:
return row["Deaths"]
# ------------------------------------------
# calautating the Final Deaths by using the new_death function
df7 = df6.copy()
df7["Deaths_2"] = df7.apply(new_death, axis=1)
# ------------------------------------------
# Cleaning the dataset
df8 = df7[
[
"State",
"State_Code",
"County",
"County_Code",
"Year",
"Population_y",
"Deaths_2",
"Original",
"State_Mortality_Rate",
]
]
# Renaming columns
df8 = df8.rename(columns={"Population_y": "Population", "Deaths_2": "Deaths"})
# ------------------------------------------
# Calculating Mortality Rate for each county, if population is 0 then mortality rate is 0
df8["County_Mortality_Rate"] = np.where(
df8["Population"] == 0, 0, df8["Deaths"] / df8["Population"]
)
# sorting the rows
df9 = df8.sort_values(by=["State", "County", "Year"]).reset_index(drop=True)
# ------------------------------------------
# Saving the Final Dataset
df9.to_parquet("data.parquet", index=False)