<jupyter_start><jupyter_text>U.S. Medical Insurance Costs **Key Objectives of this Project are:**   * Utilize the base functions of Python to do basic Data Analysis. This involves importing data from csv fies, finding missing values, summary analysis, and creating class & functions as required.   * Implement the learnings from Codecademy Python Fundamentals Module.   * Build a basic template for Data Analysis Projects.<jupyter_code># Load Libraries
import csv<jupyter_output><empty_output><jupyter_text>**insurance.csv** contains the following columns:* Patient Age* Patient Sex * Patient BMI* Patient Number of Children* Patient Smoking Status* Patient U.S Geopraphical Region* Patient Yearly Medical Insurance CostThere are no signs of missing data. To store this information, seven empty lists will be created hold each individual column of data from **insurance.csv**.<jupyter_code># Create empty lists for the various attributes in insurance.csv
ages = []
sexes = []
bmis = []
num_children = []
smoker_statuses = []
regions = []
insurance_charges = []
# Create Function to load data from csv to lists using base Python Functions
def load_list_data(lst, csv_file, column_name):
    # Open CSV File
    with open(csv_file) as csv_info:
        # Read CSV Data using DictReader Object from CSV Library
        csv_dict = csv.DictReader(csv_info)
        for row in csv_dict:
            # Append Each Row of a particular column to the list
            lst.append(row[column_name])
        # Return the List
        return lst
# Load CSV Data using Helper Function to Lists
load_list_data(ages, 'insurance.csv', 'age')
load_list_data(sexes, 'insurance.csv', 'sex')
load_list_data(bmis, 'insurance.csv', 'bmi')
load_list_data(num_children, 'insurance.csv', 'children')
load_list_data(smoker_statuses, 'insurance.csv', 'smoker')
load_list_data(regions, 'insurance.csv', 'region')
load_list_data(insurance_charges, 'insurance.csv', 'charges')<jupyter_output><empty_output><jupyter_text>**Analysis Objectives**The objectives of our data analysis are listed below:* Find Average of Patients* Find the number of males and females in the dataset* Find unique regions in the dataset* Find Average Yearly Medical Charges of Patients* Find the Average BMI of Patients* Find the number of smokers and non-smokers in the dataset* Find the number of patients with children and withoutThese objectives will be further expanded as we move deeper into the course to include more statistical analysis like correlation, variation ,distribution, etc. **Notes on Class**A class is a template for a data type. It describes the type of information the class will hold and how a programmer will interact with the data. Class lies at the foundation of Object Oriented Programming.Object is an instance of Class. Each instance of class can hold different kinds of data. The data held by an object is referred to as _instance variable_. Instance variables aren't shared by all instances of a class - they are variables that are specific to the object they are attached to.Attributes can be added to user-defined objects after instantiation, so it’s possible for an object to have some attributes that are not explicitly defined in an object’s constructor.Always remember that everything is an object. **Implementation of Patients Info Class**`PatientsInfo` Class will be created to structure the data we need and write following methods to analyze the data:* `analyze_ages`* `analyze_sexes`* `analyze_smokers`* `analyze_children`* `unique_regions`* `average_bmi`* `average_charges`* `create_dictionary` - Create a dictionary to hold all patient information<jupyter_code># Create Paitents Info Class
class PatientsInfo:
    # Using Constructor/Dunder/Init Method to prepare an object being instantiated with key data attributes 
    # that is required for every patient.
    def __init__(self, patients_ages, patients_sexes, patients_bmis, 
                patients_smoker_statuses, patients_num_children, patients_regions, patients_charges):
        self.patients_ages = patients_ages
        self.patients_sexes = patients_sexes
        self.patients_bmis = patients_bmis
        self.patients_smoker_statuses = patients_smoker_statuses
        self.patients_num_children = patients_num_children
        self.patients_regions = patients_regions
        self.patients_charges = patients_charges
    
    # Method to find average age of patients
    def analyze_ages(self):
        # intialize total age to zero
        total_age = 0
        # iterate through all ages in the ages list
        for age in self.patients_ages:
            total_age += int(age)
        # Return Average Age
        return("Average Patient Age: " + str(round(total_age/len(self.patients_ages),2)) + " years.")
    
    # Method to find number of male and female patients in dataset
    def analyze_sexes(self):
        # initialize number of males and females to zero
        females = 0
        males = 0
        for sex in self.patients_sexes:
            if sex == "female":
                females += 1
            elif sex == "male":
                males += 1
        # Print out number of females and males
        print("Number of females: ", females)
        print("Number of males: ", males)
    
    # Method to find number of smokers and number of non-smokers in dataset
    def analyze_smokers(self):
        # initialize number of smokers and nonsmokers to zero
        smokers = 0
        nonsmokers = 0
        for smoker_status in self.patients_smoker_statuses:
            if smoker_status == "yes":
                smokers += 1
            elif smoker_status == "no":
                nonsmokers += 1
        # Print out number of females and males
        print("Number of Smokers: ", smokers)
        print("Number of Non-Smokers: ", nonsmokers)
    
    # Method to find number of patients with children and number of patients without children in dataset
    def analyze_children(self):
        # initialize patients with children and patients without children to zero
        with_children = 0
        without_cildren = 0
        for num_children in self.patients_num_children:
            if int(num_children) > 0:
                with_children += 1
            else:
                without_cildren += 1
        # Print out number of females and males
        print("Number of Patients with Children: ", with_children)
        print("Number of Patients without Children: ", without_cildren)
    
    # Method to find number of unique regions in dataset
    def find_unique_regions(self):
        # Intialize Empty List
        unique_regions = []
        # Iterate through each region in regions list
        for region in self.patients_regions:
            # If Region is not in Unique Regions Lis
            # Add to it
            if region not in unique_regions:
                unique_regions.append(region)
        # Return Unique Regions List
        return unique_regions
    
    # Method to find average BMI of patients in dataset
    def average_bmi(self):
        # intialize total bmi to zero
        total_bmi = 0
        # iterate through all BMIs in the BMI list
        for bmi in self.patients_bmis:
            total_bmi += float(bmi)
        # Return Average BMI
        return("Average Patient BMI: " + str(round(total_bmi/len(self.patients_bmis),2)) + ".")
    
    # Method to find average yearly medical insurance charges of patients in dataset
    def average_charges(self):
        # intialize total charges to zero
        total_charges = 0
        # iterate through all BMIs in the BMI list
        for charges in self.patients_charges:
            total_charges += float(charges)
        # Return Average BMI
        return("Average Yearly Medical Insurance Charges: " + str(round(total_charges/len(self.patients_charges),2)) + ".")
    
    # Method to create dictionary to hold key patient attributes
    def create_dictionary(self):
        self.patients_dictionary = {}
        self.patients_dictionary["age"] = [int(age) for age in self.patients_ages]
        self.patients_dictionary["sex"] = self.patients_sexes
        self.patients_dictionary["bmi"] = self.patients_bmis
        self.patients_dictionary["children"] = self.patients_num_children
        self.patients_dictionary["smoker"] = self.patients_smoker_statuses
        self.patients_dictionary["regions"] = self.patients_regions
        self.patients_dictionary["charges"] = self.patients_charges
        return self.patients_dictionary
# Create an instance of PatientInfo Class
patient_info = PatientsInfo(ages,sexes,bmis,smoker_statuses,num_children,regions,insurance_charges)
# Find Average Age of Patients in Dataset
patient_info.analyze_ages()<jupyter_output><empty_output><jupyter_text>Average Age of a Patient is around 39 years. This is done to ensure that the dataset is representative of the intended population being analyzed<jupyter_code># Find Number of Males and Females in Dataset
patient_info.analyze_sexes()<jupyter_output>Number of females:  662
Number of males:  676<jupyter_text>From the result, it can be inferred that the dataset is a balanced one and not a biased/unbalanced dataset.<jupyter_code># Find Number of Smokers and Non-Smokers in Dataset
patient_info.analyze_smokers()<jupyter_output>Number of Smokers:  274
Number of Non-Smokers:  1064<jupyter_text>This data is unbalanced in terms of the smokers. It needs to be balanced if analysis needs to be done specific to understand the impact of smoking on Charges.<jupyter_code># Find Patients with Children and Without Children
patient_info.analyze_children()<jupyter_output>Number of Patients with Children:  764
Number of Patients without Children:  574<jupyter_text>From the result, it can be inferred that dataset is nearly balanced one.<jupyter_code># Find Average BMI of Patients
patient_info.average_bmi()
# Find Average BMI of Patients
patient_info.average_charges()
# Create Dictionary for further analysis
patient_info.create_dictionary()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.06376407293015841, 'fraction_numerical': 0.003985254558134901, 'mean_word_length': 3.519585772174696, 'pattern_counts': {'":': 4, '<': 26, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '164592', 'license': 'MIT', 'n_tokens_mistral': 2803, 'n_tokens_neox': 2602, 'n_words': 1042, 'path': 'Notebooks/us-medical-insurance-costs/us-medical-insurance-costs.ipynb', 'repo_name': 'mayanklal/codecademy-dscp-notebooks', 'size': '10037'}