Home > database >  How to get an average mean of columns Flask/Pandas
How to get an average mean of columns Flask/Pandas

Time:07-03

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:

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.

CodePudding user response:

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

  • Related