Data Analysis with Python Projects - Medical Data Visualizer

Tell us what’s happening:
Hello,

I am trying to submit my code that I wrote locally however, I cannot follow the below steps;

Start by importing the project on Replit.
Next, you will see a .replit window.
Select Use run command and click the Done button.

The “Use run command” is not present. Please advise

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0

Challenge: Data Analysis with Python Projects - Medical Data Visualizer

Link to the challenge:

You could enter python3 main.py here

Or edit the line in the .replit file (might need to show hidden files) to be:

run = “python3 main.py”

Thank you for your response,

If I comment out the below lines my code will run locally in Visual Studio.

#fig.savefig(‘heatmap.png’)
fig.savefig(‘catplot.png’)

However, if I run the code below it throws an error

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

Import data

df = pd.read_csv(“medical_examination.csv”)

#calculate their BMI by dividing their weight in kilograms by the square of their height in meters.

If that value is > 25 then the person is overweight. Use the value 0 for NOT overweight and the value 1 for overweight.

df[‘overweight’] = df.apply(lambda x: 1 if(x.weight / ((x.height / 100)**2) > 25) else 0, axis=1)

Normalize data by making 0 always good and 1 always bad.

If the value of ‘cholesterol’ or ‘gluc’ is 1, make the value 0.

If the value is more than 1, make the value 1.

df[‘gluc’] = df.apply(lambda p: 1 if(p.gluc > 1) else 0, axis=1)
df[‘cholesterol’] = np.where(df.cholesterol > 1, 1,0)

Draw Categorical Plot

def draw_cat_plot():
# Create DataFrame for cat plot using pd.melt using just the values from ‘cholesterol’, ‘gluc’, ‘smoke’, ‘alco’, ‘active’, and ‘overweight’.
df_cat= sorted([‘cholesterol’, ‘gluc’, ‘smoke’, ‘alco’, ‘active’,‘overweight’])

# Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the columns for the catplot to work correctly.
df_cat = df.melt(id_vars='cardio', value_vars=df_cat)


# Draw the catplot with 'sns.catplot()'
sns.catplot(x='variable', col='cardio', hue='value',kind='count', data=df_cat).set_axis_labels('variable', 'Total')


# Get the figure for the output
fig = df_cat.plot.bar



# Do not modify the next two lines
fig.savefig('catplot.png')
return fig

draw_cat_plot()

Draw Heat Map

def draw_heat_map():
# Clean/filter the data
df_heat = df.loc[(df[‘ap_lo’] <= df[‘ap_hi’]) &
(df[‘height’] >= df[‘height’].quantile(0.025)) &
(df[‘height’] <= df[‘height’].quantile(0.975)) &
(df[‘weight’] >= df[‘weight’].quantile(0.025))&
(df[‘weight’] <= df[‘weight’].quantile(0.975))]

# Calculate the correlation matrix
corr = df_heat.corr()

# Generate a mask for the upper triangle
mask = np.zeros_like(corr)
mask[(np.triu_indices_from(mask))]=True



# Set up the matplotlib figure
fig, ax = plt.subplots(figsize=(10,10))

# Draw the heatmap with 'sns.heatmap()'
ax = sns.heatmap(corr, vmin=0, vmax=0.25, annot=True, fmt='.1f', linewidths=0, square=True, mask=mask)



# Do not modify the next two lines
fig.savefig('heatmap.png')
return fig

Any help would be greatly appreciated, I have run out of ideas.

Would you mind formatting your code using the “code” icon here (or wrapping in triple backticks)

Or link to your replit?
Screenshot 2023-09-03 082302

No problem, thanks

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Import data
df = pd.read_csv("medical_examination.csv")

#calculate their BMI by dividing their weight in kilograms by the square of their height in meters. 
# If that value is > 25 then the person is overweight. Use the value 0 for NOT overweight and the value 1 for overweight.

df['overweight'] = df.apply(lambda x: 1 if(x.weight / ((x.height / 100)**2) > 25) else 0, axis=1)

# Normalize data by making 0 always good and 1 always bad. 
# If the value of 'cholesterol' or 'gluc' is 1, make the value 0.
#  If the value is more than 1, make the value 1.

df['gluc'] = df.apply(lambda p: 1 if(p.gluc > 1) else 0, axis=1)
df['cholesterol'] = np.where(df.cholesterol > 1, 1,0)



# Draw Categorical Plot
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat= sorted(['cholesterol', 'gluc', 'smoke', 'alco', 'active','overweight'])

    
    
    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the columns for the catplot to work correctly.
    df_cat = df.melt(id_vars='cardio', value_vars=df_cat)
    

    # Draw the catplot with 'sns.catplot()'
    sns.catplot(x='variable', col='cardio', hue='value',kind='count', data=df_cat).set_axis_labels('variable', 'Total')


    # Get the figure for the output
    fig = df_cat.plot.bar
    


    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig
draw_cat_plot()


# Draw Heat Map
def draw_heat_map():
    # Clean/filter the data
    df_heat = df.loc[(df['ap_lo'] <= df['ap_hi']) &
    (df['height'] >= df['height'].quantile(0.025)) &
    (df['height'] <= df['height'].quantile(0.975)) &
    (df['weight'] >= df['weight'].quantile(0.025))&
    (df['weight'] <= df['weight'].quantile(0.975))]


 
    
    


    # Calculate the correlation matrix
    corr = df_heat.corr()

    # Generate a mask for the upper triangle
    mask = np.zeros_like(corr)
    mask[(np.triu_indices_from(mask))]=True



    # Set up the matplotlib figure
    fig, ax = plt.subplots(figsize=(10,10))

    # Draw the heatmap with 'sns.heatmap()'
    ax = sns.heatmap(corr, vmin=0, vmax=0.25, annot=True, fmt='.1f', linewidths=0, square=True, mask=mask)



    # Do not modify the next two lines
    fig.savefig('heatmap.png')
    return fig

are you still getting the "has no attribute 'startswith'" error?

I’m not able to replicate it. I would examine these lines though:

    sns.catplot(x='variable', col='cardio', hue='value',kind='count', data=df_cat).set_axis_labels('variable', 'Total')
    fig = df_cat.plot.bar

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.