Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get an average mean of columns Flask/Pandas

I need to calculate an average of two columns ‘Height(Inches)’ and ‘Weight(Pounds)’, when i use the code below , i getting the error 500 ‘Internal Server Error’.

@app.route('/csv')
def get_average_parameters():
dataset = pd.read_csv('hw.csv')
average = dataset[['Height(Inches)', 'Weight(Pounds)']].mean()
return str(average)

But when use ‘average’ without columns sigs:

@app.route('/csv')
def get_average_parameters():
dataset = pd.read_csv('hw.csv')
average = dataset.mean()
return str(average)

I didn’t get any error, and output looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Index 12500.500000 Height(Inches) 67.993114 Weight(Pounds) 127.079421 dtype: float64

How i can get the averages of two columns ‘Height(Inches)’ and ‘Weight(Pounds)’ without errors?

Thx in advance.

>Solution :

The second way is correct, but it’s wrong that you return the value directly as a string. dataset.mean() returns a series, that is why your output looks like that. In order to just get the mean of certain column, lets say height column, you just have to do it like this


average['Height(Inches)']

So you can modify your return statement like this


return f"Average Height: {average['Height(Inches)']}, Average Weight: {average['Weight(Pounds)']}"

Or if you just want to return in a shape of array you can


return f"{average.values[1:]}"

Why starts with 1? because index 0 is your dataframe index

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading