【问题标题】:Create Average of Monthly Data to Quaterly Data in Panel Data using Pandas使用 Pandas 在面板数据中创建月度数据到季度数据的平均值
【发布时间】:2021-07-07 01:50:57
【问题描述】:

我有以下数据集:

     Date Country         Specie  Monthly Average  \
 Apr 2015       BR             co         5.840000   
 Apr 2015       BR            no2         7.553704   
 Apr 2015       BR             o3        15.561667   
 Apr 2015       BR           pm10        16.283333   
 Apr 2015       BR           pm25        51.633333   

... ... ... ... ...

对于 10 个国家,对于 2015 年至 2021 年月份的某些排放量(物种)。我想将它们转换为以下形式的季度平均数据(使用一个季度中相应月份的平均值)为例:

     Date Country         Specie  Quarterly Average  \
 2015 Q1       BR             co         6.840000   
 2015 Q1       BR            no2         9.553704   
 2015 Q1       BR             o3        17.561667   
 2015 Q1       BR           pm10        18.283333   
 2015 Q1       BR           pm25        55.633333   

... ... ... ... ...

如何在 python pandas 中做到这一点?

另外我还有一个问题,如果我想在列中分离 Specie 并取相应的值,这怎么可能,我可以获得以下结构:

     Date Country         co Average       no2 Average   o3 Average      ...    \
 2015 Q1       BR           6.840000      9.553704   17.561667 
 2015 Q2       BR           8.840000      10.553704   18.561667 

【问题讨论】:

    标签: python pandas converters panel-data


    【解决方案1】:

    首先从原始Date 列创建一个Quarter

    df['Quarter'] = pd.to_datetime(df['Date']).dt.to_period('Q')
    

    然后通过CountrySpecieQuarter 列分组,计算每个组中Monthly Average 列的平均值。将结果列重命名为Quarterly Average

    df_ = df.groupby(['Country', 'Specie', 'Quarter'], as_index=False)['Monthly Average'].mean().rename(columns={'Monthly Average': 'Quarterly Average'})
    

    仅供参考,pandas.pivot_table() 是您想要获得的结构。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2019-08-13
    • 2021-01-07
    • 2020-08-28
    • 1970-01-01
    • 2015-12-22
    • 2023-01-28
    • 2020-11-23
    • 1970-01-01
    • 2020-12-29
    相关资源
    最近更新 更多