【问题标题】:How to get an average mean of columns Flask/Pandas如何获得 Flask/Pandas 列的平均平均值
【发布时间】:2022-08-14 23:46:13
【问题描述】:

我需要计算两列 \'Height(Inches)\' 和 \'Weight(Pounds)\' 的平均值,当我使用下面的代码时,我收到错误 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)

但是当使用没有列的 \'average\' 时:

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

我没有收到任何错误,输出如下所示:

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

如何在没有错误的情况下获得两列 \'Height(Inches)\' 和 \'Weight(Pounds)\' 的平均值?

    标签: python pandas


    【解决方案1】:

    第二种方式是正确的,但是直接将值作为字符串返回是错误的。 dataset.mean() 返回一个系列,这就是你的输出看起来像这样的原因。为了得到某个列的平均值,比如说高度列,你只需要这样做

    
    average['Height(Inches)']
    
    

    所以你可以像这样修改你的退货声明

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

    或者,如果您只想以数组的形式返回,您可以

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

    为什么从 1 开始?因为索引 0 是您的数据帧索引

    【讨论】:

      猜你喜欢
      • 2012-03-18
      • 2015-09-11
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多