Import the necessary libraries:
Import pandas as pd: Imports the Pandas library and assigns it the alias ‘pd’.
import matplotlib.pyplot as plt: Imports the Matplotlib library, specifically the ‘pyplot’ module, and assigns it the alias ‘plt’. Matplotlib is used for creating plots and visualizations.
Load the Excel file into a Data Frame:
directory_path: Specifies the file path to the Excel file you want to load. Make sure to update this path to the location of your Excel file.
sheet_name: Specifies the name of the sheet within the Excel file from which data should be read.
df = pd.read_excel(directory_path, sheet_name=sheet_name): Uses the pd.read_excel function to read the data from the Excel file into a Pandas DataFrame named ‘df’.
Calculate the median age of all individuals:
Median_age = df[‘age’].median(): Calculates the median age of all individuals in the ‘age’ column of the DataFrame and stores it in the ‘median_age’ variable.
print(“Median Age of All Individuals:”, median_age): Prints the calculated median age to the console.
Create age groups:
age_bins: Defines the boundaries for age groups. In this case, individuals will be grouped into the specified age ranges.
age_labels: Provides labels for each age group, corresponding to the ‘age_bins’.
Cut the age data into age groups:
df[‘Age Group’] = pd.cut(df[‘age’], bins=age_bins, labels=age_labels): Creates a new column ‘Age Group’ in the DataFrame by categorizing individuals’ ages into the age groups defined in ‘age_bins’ and labeling them with ‘age_labels.’
Count the number of individuals in each age group:
age_group_counts = df[‘Age Group’].value_counts().sort_index(): Counts the number of individuals in each age group and sorts them by the age group labels. The result is stored in the ‘age_group_counts’ variable.
Create a bar graph to analyze age groups:
plt.figure(figsize=(10, 6): Sets the size of the figure for the upcoming plot.
age_group_counts.plot(kind=’bar’, color=’skyblue’): Plots a bar graph using the ‘age_group_counts’ data, where each bar represents an age group. ‘skyblue’ is the color of the bars.
plt.title(‘Age Group Analysis’): Sets the title of the plot.
plt.xlabel(‘Age Group’): Sets the label for the x-axis.
plt.ylabel(‘Number of Individuals’): Sets the label for the y-axis.
plt.xticks(rotation=45): Rotates the x-axis labels by 45 degrees for better readability.
plt.show(): Displays the bar graph on the screen.