【问题标题】:pandas: finding the average of a selected column熊猫:查找所选列的平均值
【发布时间】:2015-01-21 05:22:42
【问题描述】:

这是我的 DataFrame 的前 15 个元素

我需要的是平均 (column(Total Rainfall) per year(column (Year))。我拥有的数据集包含截至 2011 年的降雨量。

有人可以帮忙吗?

稍后我想绘制从 1962 年到 2011 年的年平均值。

In [143]: df.head(15)

Out[143]:

   Total Rainfall       Year  
0           134.6       1962  
1            77.2       1962  
2            73.6       1962  
3            68.6       1962  
4            80.7       1962  
5            50.2       1962  
6            92.2       1962  
7            99.4       1962  
8           122.4       1962  
9            42.6       1962  
10          105.5       1962  
11           86.4       1962  
12           34.8       1963  
13           96.0       1963  
14          212.5       1963  

【问题讨论】:

    标签: python pandas dataframe plot mean


    【解决方案1】:

    您可以为此使用groupby。使用您提供的数据:

     >>> df.groupby('Year').mean()
            Rainfall
    Year            
    1962   86.116667
    1963  114.433333
    

    Pandas 的 groupby 方法按特定列中的值对 DataFrame 进行分组,并使用特定函数(在本例中为 mean)聚合其他列中的数值数据。

    要绘制此数据,您可以使用 plot 并指定所需的图表类型:

    >>> df.groupby('Year').mean().plot(kind='bar');
    

    生成此条形图:

    【讨论】:

    • 我知道这很简单!非常感谢ajcr。
    猜你喜欢
    • 2015-09-11
    • 2023-02-17
    • 2016-03-03
    • 1970-01-01
    • 2021-03-10
    • 2015-07-18
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多