【问题标题】:How do I iterate through pandas dataframe and calculate average?如何遍历熊猫数据框并计算平均值?
【发布时间】:2021-07-19 02:32:30
【问题描述】:

Temperature Dataframe

我有一个 pandas 数据框,其中记录了 1953 年和 1954 年每个月的最高温度和最低温度。现在我想计算每年的平均最高和最低温度值(例如,每年总结最高温度) 12 个月的温度除以 12)。我该怎么做?

【问题讨论】:

  • 请以文本而非图像的形式提供输入和输出数据框

标签: python pandas dataframe loops


【解决方案1】:

试试-

import numpy as np
df  = df.groupby('Year', as_index=False).agg({'MaxTemperature': np.mean, 'MinTemperature' : np.mean})

【讨论】:

    【解决方案2】:

    考虑到您不需要输出中的“月份”列,并且需要按年份计算最高和最低温度的平均值。

    解决方案

    df.groupby('Year',as_index=False).mean().drop(columns='Month')

    输入

        Year    Month   MaxTemperature  MinTemperature
    0   1953    1       26.7            10.9
    1   1954    2       29.2            9.9
    2   1953    1       27.4            11.0
    3   1954    2       28.0            11.2
    4   1953    1       28.0            13.0
    5   1954    2       25.4            9.4
    6   1953    1       26.0            12.0
    7   1954    2       29.1            10.5
    

    输出

        Year    MaxTemperature  MinTemperature
    0   1953      27.025          11.725
    1   1954      27.925          10.250
    

    【讨论】:

    • 非常感谢!这是完美的答案。
    • 太棒了,在这种情况下,您可以选择对答案进行投票并通过单击对勾来接受它作为预期答案。
    猜你喜欢
    • 2018-10-26
    • 1970-01-01
    • 2017-08-22
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多