<jupyter_start><jupyter_text>Observations and Insights<jupyter_code># Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import scipy.stats as st

# Study data files
mouse_metadata_path = "data/Mouse_metadata.csv"
study_results_path = "data/Study_results.csv"

# Read the mouse data and the study results
mouse_metadata = pd.read_csv(mouse_metadata_path)
study_results = pd.read_csv(study_results_path)



# Combine the data into a single dataset
merge_df = pd.merge(mouse_metadata,study_results, on="Mouse ID" )
merge_df
# Display the data table for preview

# Checking the number of mice.
df = merge_df
df['Mouse ID'].nunique()
# Getting the duplicate mice by ID number that shows up for Mouse ID and Timepoint. 

dup_df = df[df.duplicated(subset=['Mouse ID', 'Timepoint'],keep=False)]
dup_df

# Optional: Get all the data for the duplicate mouse ID. 


# Create a clean DataFrame by dropping the duplicate mouse by its ID.

clean_df = df.loc[df['Mouse ID'] != 'g989']
clean_df
# Checking the number of mice in the clean DataFrame.
clean_df['Mouse ID'].nunique()<jupyter_output><empty_output><jupyter_text>Summary Statistics<jupyter_code># Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen
tumor_volume_drug = clean_df.groupby('Drug Regimen')

td_mean = tumor_volume_drug['Tumor Volume (mm3)'].mean()
td_median = tumor_volume_drug['Tumor Volume (mm3)'].median()
td_variance = tumor_volume_drug['Tumor Volume (mm3)'].var()
td_standard = tumor_volume_drug['Tumor Volume (mm3)'].std()
td_sem = tumor_volume_drug['Tumor Volume (mm3)'].sem()

# Use groupby and summary statistical methods to calculate the following properties of each drug regimen: 
# mean, median, variance, standard deviation, and SEM of the tumor volume. 
# Assemble the resulting series into a single summary dataframe.

tdf = pd.DataFrame({'Mean': td_mean, 'Median' : td_median, 'Variance' : td_variance, 'Standard':td_standard, 'SEM':td_sem})
                                      
tdf

# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen
df4 = (clean_df.groupby(['Drug Regimen'])['Tumor Volume (mm3)']
         .agg(['mean','median','std','sem'])
         .reset_index())
print (df4)
# Using the aggregation method, produce the same summary statistics in a single line<jupyter_output>Drug Regimen       mean     median       std       sem
0    Capomulin  40.675741  41.557809  4.994774  0.329346
1     Ceftamin  52.591172  51.776157  6.268188  0.469821
2    Infubinol  52.884795  51.820584  6.567243  0.492236
3     Ketapril  55.235638  53.698743  8.279709  0.603860
4     Naftisol  54.331565  52.509285  8.134708  0.596466
5      Placebo  54.033581  52.288934  7.821003  0.581331
6     Propriva  52.320930  50.446266  6.622085  0.544332
7     Ramicane  40.216745  40.673236  4.846308  0.320955
8     Stelasyn  54.233149  52.431737  7.710419  0.573111
9    Zoniferol  53.236507  51.818479  6.966589  0.516398<jupyter_text>Bar and Pie Charts<jupyter_code># Generate a bar plot showing the total number of measurements taken on each drug regimen using pandas.
drug_df = clean_df['Drug Regimen'].value_counts()
ax = drug_df.plot.bar()
# Generate a bar plot showing the total number of measurements taken on each drug regimen using pyplot.

  
# Creating plot 
drug_df.plot(x = 'Drug Regimen', y='Measurements of each Regimen', kind = 'bar')
plt.ylabel('Measurements of Drug Regimen')
plt.xlabel(' Drug Regimen')

# show plot 
plt.show()
# Generate a pie plot showing the distribution of female versus male mice using pandas
labels = ['Male', 'Female']
gender_type = clean_df['Sex'].value_counts()
print(gender_type)

plt.pie(gender_type, labels=labels, shadow=True)

#px = drug_df.plot.pie(subplots=True)
# Generate a pie plot showing the distribution of female versus male mice using pyplot
mice_gender = gender_type.plot(kind='pie')

plt.show()

# Calculate the final tumor volume of each mouse across four of the treatment regimens:  
tp_max = clean_df.groupby('Mouse ID')['Timepoint'].max()
tp_max<jupyter_output><empty_output><jupyter_text>Quartiles, Outliers and Boxplots<jupyter_code># Calculate the final tumor volume of each mouse across four of the treatment regimens:  
# Capomulin, Ramicane, Infubinol, and Ceftamin
drug_reg = (df['Drug Regimen']=='Capomulin')& (df['Drug Regimen']=='Ramicane')&(df['Drug Regimen']=='Infubinol')& (df['Drug Regimen']=='Ceftamin')
# Start by getting the last (greatest) timepoint for each mouse
time_slot = drug_reg['Timepoint']
quartiles = time_slot.quantile()
lowerq = quantiles[0]
upperq = quantiles[45]
print(f"The lower quartile of Timepoint is: {lowerq}")
print(f"The upper quartile of Timepoint is: {upperq}")

# Merge this group df with the original dataframe to get the tumor volume at the last timepoint

# Put treatments into a list for for loop (and later for plot labels)
drug_treatments=["Capomulin", "Ramicane", "ketapril", "Infubinol"]

# Create empty list to fill with tumor vol data (for plotting)
tumor_vol =[]

# Calculate the IQR and quantitatively determine if there are any potential outliers. 
    
    # Locate the rows which contain mice on each drug and get the tumor volumes
for drug in drug_treatments:   
    tumor_drug = df.loc[df["Drug Regimen"]==drug, 'Tumor Volume (mm3)']
    
    # add subset 
    tumor_vol.append(tumor_drug)
    
    # Determine outliers using upper and lower bounds
    quartiles = tumor_drug.quantile([.25,.5,.75])
    lower_q=quartiles[0.25]
    upper_q=quartiles[0.75]
    iqr=upper_q-lower_q
    lower_bound=lower_q - (1.5*iqr)
    upper_bound=upper_q + (1.5*iqr)
    outliers = tumor_drug.loc[(tumor_drug<lower_bound)| (tumor_drug>upper_bound)]
    print(f"{drug}'s potential outliers: {outliers}")
    
# Generate a box plot of the final tumor volume of each mouse across four regimens of interest

#cap_reg =df.loc[((df['Drug Regimen']=='Capomulin') & (df['Drug Regimen']=='Ramicane') & (df['Drug Regimen']=='ketapril') & (df['Drug Regimen']=='Naftisol'))]<jupyter_output><empty_output><jupyter_text>Line and Scatter Plots<jupyter_code># Generate a line plot of tumor volume vs. time point for a mouse treated with Capomulin
cap_reg = df.loc[df['Drug Regimen'] == 'Capomulin']
mice_reg = cap_reg.loc[cap_reg['Mouse ID']=='S185']

plt.plot(mice_reg['Timepoint'],mice_reg['Tumor Volume (mm3)'])
plt.xlabel('Timepoint')
plt.ylabel('Tumor Volume (mm3)')
plt.title('Mouse S185 Treatment Capomulin')
plt.show()
# Generate a scatter plot of average tumor volume vs. mouse weight for the Capomulin regimen
average=cap_reg.groupby(['Mouse ID']).mean()
plt.scatter(average['Weight (g)'], average['Tumor Volume (mm3)'])
plt.xlabel('Weight (g)')
plt.ylabel('Average Tumor Volume (mm3)')
plt.title('Capomulin regimen')
plt.show()<jupyter_output><empty_output><jupyter_text>Correlation and Regression<jupyter_code># Calculate the correlation coefficient and linear regression model 
# for mouse weight and average tumor volume for the Capomulin regimen
correlation = round(st.pearsonr(average['Weight (g)'], average['Tumor Volume (mm3)'])[0],2)
print(f"Correlation between weight and average tumor volume is {correlation}")
model=st.linregress(average['Weight (g)'], average['Tumor Volume (mm3)'])
y_values=average['Weight (g)']*model[0]+model[1]
x_values=average['Weight (g)']
plt.scatter(x_values, average['Tumor Volume (mm3)'])
plt.plot(x_values, y_values, color="yellow")
plt.xlabel('Weight (g)')
plt.ylabel('Tumor Volume (mm3) Average')
plt.show()<jupyter_output>Correlation between weight and average tumor volume is 0.84
StarcoderdataJupyterStructuredCleanDedup