Challenge

Project 2 - EDA on Vehicle Insurance Customer Data

#1

)# Input customer data
customer_id = input("Enter customer_id: ")
gender = input("Enter Gender (M/F): ")
age = int(input("Enter age: "))
driving_licence_present = input("Is driving licence present (Y/N): ")
region_code = input("Enter region code: ")
previously_insured = input("Is previously insured (Y/N): ")
vehicle_age = input("Enter vehicle age: ")
vehicle_damage = input("Is vehicle damage (Y/N): ")

# Perform operations on customer data
# For example, you can perform data validation, calculations, or data manipulation here
# Here, we're just printing the entered data

print("Customer ID:", customer_id)
print("Gender:", gender)
print("Age:", age)
print("Driving Licence Present:", driving_licence_present)
print("Region Code:", region_code)
print("Previously Insured:", previously_insured)
print("Vehicle Age:", vehicle_age)
print("Vehicle Damage:", vehicle_damage)
2)
# Function to calculate annual premium
def calculate_annual_premium(age, gender, sum_insured):
base_premium = 1000 # Base premium amount
if age < 18:
return 0 # No premium for customers below 18 years of age
elif age >= 18 and age < 30:
premium = base_premium + (sum_insured * 0.05) # 5% additional premium for customers aged 18-29
elif age >= 30 and age < 45:
premium = base_premium + (sum_insured * 0.03) # 3% additional premium for customers aged 30-44
else:
premium = base_premium + (sum_insured * 0.01) # 1% additional premium for customers aged 45 and above

if gender.lower() == 'male':
premium *= 1.2 # 20% additional premium for male customers

return premium


# Function to determine sales channel code
def determine_sales_channel(age, gender):
if age < 25 and gender.lower() == 'male':
return 'A' # Sales channel A for male customers below 25 years of age
elif age >= 25 and age < 35:
return 'B' # Sales channel B for customers aged 25-34
else:
return 'C' # Sales channel C for customers aged 35 and above


# Function to determine vintage
def determine_vintage(customer_id):
# Assuming customer_id is a unique identifier for each customer
# and vintage is calculated based on the length of the customer_id
vintage = len(customer_id)
return vintage


# Input customer data
customer_id = input("Enter customer ID: ")
age = int(input("Enter customer age: "))
gender = input("Enter customer gender (male/female): ")
sum_insured = float(input("Enter sum insured amount: "))

# Calculate annual premium
annual_premium = calculate_annual_premium(age, gender, sum_insured)

# Determine sales channel code
sales_channel = determine_sales_channel(age, gender)

# Determine vintage
vintage = determine_vintage(customer_id)

# Generate response
response = f"Customer ID: {customer_id}\nAnnual Premium (in Rs): {annual_premium}\nSales Channel Code: {sales_channel}\nVintage: {vintage} years"

# Print response
print(response)

#2


# Load your data into a pandas DataFrame (assuming your DataFrame is named 'df')
df = pd.read_csv('your_data.csv')

# Generate summary of count of null values column-wise
null_counts = df.isnull().sum()

# Drop null values for 'customer_id' column
df.dropna(subset=['customer_id'], inplace=True)

# Replace null values for numeric columns with mean
numeric_cols = df.select_dtypes(include='number').columns
df[numeric_cols] = df[numeric_cols].fillna(df[numeric_cols].mean())

# Replace null values for categorical columns with mode
categorical_cols = df.select_dtypes(include='object').columns
df[categorical_cols] = df[categorical_cols].fillna(df[categorical_cols].mode().iloc[0])

# Print the summary of count of null values column-wise
print("Summary of count of null values column-wise:")
print(null_counts)

# Print the updated DataFrame
print("Updated DataFrame:")
print(df.head())
ii)
import pandas as pd

# Load the dataset
df = pd.read_csv('your_dataset.csv')
iii)
def remove_white_spaces(input_string):
"""Removes white spaces from a given input string."""
return "".join(input_string.split())

# Input string
input_string = " This is a string with white spaces. "
print("Original string:", input_string)

# Remove white spaces
output_string = remove_white_spaces(input_string)
print("String without white spaces:", output_string)
iv)
def case_correction(text, case):
"""
Corrects the case of a given text based on the specified case parameter.
:param text: The text to be corrected.
:param case: The case to convert to. Can be 'lower' or 'upper'.
:return: The corrected text.
"""
if case == 'lower':
corrected_text = text.lower()
elif case == 'upper':
corrected_text = text.upper()
else:
raise ValueError("Invalid case parameter. Must be 'lower' or 'upper'.")
return corrected_text


# Example usage
input_text = "This is an EXAMPLE Text for CASE Correction"
desired_case = "lower" # or "upper"
corrected_text = case_correction(input_text, desired_case)
print(f"Original Text: {input_text}")
print(f"Corrected Text ({desired_case} case): {corrected_text}")
v)
import pandas as pd

# Create a sample dataframe with nominal data
data = {'City': ['New York', 'Los Angeles', 'Chicago', 'San Francisco'],
'Country': ['USA', 'USA', 'USA', 'USA']}
df = pd.DataFrame(data)

# Convi)
vert nominal data into dummy variables
df = pd.get_dummies(df, drop_first=True)

# Display the resulting dataframe
print(df)
vi)import pandas as pd

# Sample DataFrame with duplicated rows
df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'Alice', 'Bob'],
'Age': [25, 30, 35, 25, 30],
'City': ['New York', 'Los Angeles', 'Chicago', 'New York', 'Los Angeles']})

print("Original DataFrame:")
print(df)

# Drop duplicates based on all columns
df = df.drop_duplicates()

print("\nDataFrame after dropping duplicates based on all columns:")
print(df)

# Drop duplicates based on a specific column
df = df.drop_duplicates(subset='Name')

print("\nDataFrame after dropping duplicates based on 'Name' column:")
print(df)

#3

import pandas as pd

# Load customer table
customer_table = pd.read_csv("customer.csv") # Replace with the actual file name or data source for customer table

# Load customer_policy table
customer_policy_table = pd.read_csv("customer_policy.csv") # Replace with the actual file name or data source for customer_policy table

# Perform inner join on customer_id
master_table = pd.merge(customer_table, customer_policy_table, on="customer_id", how="inner")

# Display master table
print(master_table.head())

#4

import pandas as pd
table into a pandas DataFrame
master_table = pd.read_csv('master_table.csv') # Replace 'master_table.csv' with the actual file name or path

# Calculate gender-wise average annual premium
gender_avg_premium = master_table.groupby('gender')['annual_premium'].mean()

# Calculate age-wise average annual premium
age_avg_premium = master_table.groupby('age')['annual_premium'].mean()

# Check if data is balanced between genders
gender_counts = master_table['gender'].value_counts()
is_data_balanced = gender_counts[0] == gender_counts[1]

# Calculate vehicle age-wise average annual premium
vehicle_age_avg_premium = master_table.groupby('vehicle_age')['annual_premium'].mean()

# Display the calculated information
print("Gender-wise average annual premium:")
print(gender_avg_premium)

print("\nAge-wise average annual premium:")
print(age_avg_premium)

print("\nIs the data balanced between genders?")
print("Yes" if is_data_balanced else "No")

print("\nVehicle age-wise average annual premium:")
print(vehicle_age_avg_premium)

#5

import pandas as pd
import numpy as np

# Load the data into a pandas DataFrame
data = pd.read_csv('data.csv') # Replace 'data.csv' with the name of your file

# Extract the relevant columns for Person Age and annual premium
person_age = data['Person Age']
annual_premium = data['Annual Premium']

# Calculate the correlation coefficient
correlation_coefficient = np.corrcoef(person_age, annual_premium)[0][1]

# Print the correlation coefficient
print("Correlation coefficient between Person Age and Annual Premium: ", correlation_coefficient)

# Determine the relationship based on the correlation coefficient
if correlation_coefficient < -0.5:
print("Strong negative relationship")
elif correlation_coefficient > 0.5:
print("Strong positive relationship")
else:
print("There is no relationship")

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.