如何从每日数据框中计算每月的年度平均值,并按缩写的月份进行绘制

时间:2020-07-11 02:57:29

标签: python pandas matplotlib pandas-groupby

我有几年的每天降水和温度的值。我想计算一年中每个月(1月至12月)的平均降水量和平均气温。对于降水量,我首先需要计算每个月的每日降水量总和,然后计算所有年份的数据在同一月的平均值。对于温度,我需要将这些值的每月平均值平均(因此,所有月份的所有数据的平均值都得出完全相同的结果)。完成此操作后,我需要使用缩写的几个月来绘制两组数据(降水和温度)。

我找不到找到降水量值的方法,也无法求出每个月的总和,然后对所有年份进行平均。此外,我无法在短短几个月内显示该格式。

这是我到目前为止尝试过的(未成功):

import pandas as pd

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

example = [['01.10.1965 00:00', 13.88099957,    5.375],
    ['02.10.1965 00:00',    5.802999973,    3.154999971],
    ['03.10.1965 00:00',    9.605699539,    0.564999998],
    ['14.10.1965 00:00',    0.410299987,    1.11500001],
    ['31.10.1965 00:00',    6.184500217,    -0.935000002],
    ['01.11.1965 00:00',    0.347299993,    -5.235000134],
    ['02.11.1965 00:00',    0.158299997,    -8.244999886],
    ['03.11.1965 00:00',    1.626199961,    -3.980000019],
    ['24.10.1966 00:00',    0,              3.88499999],
    ['25.10.1966 00:00',    0.055100001,    1.279999971],
    ['30.10.1966 00:00',    0.25940001,     -5.554999828]]

names = ["date","Pobs","Tobs"]
data = pd.DataFrame(example, columns=names)
data['date'] = pd.to_datetime(data['date'], format='%d.%m.%Y %H:%M')

#I think the average of temperature is well computed but the precipitation would give the complete summation for all years!
tempT = data.groupby([data['date'].dt.month_name()], sort=False).mean().eval('Tobs')
tempP = data.groupby([data['date'].dt.month_name()], sort=False).sum().eval('Pobs') 

fig = plt.figure(); ax1 = fig.add_subplot(1,1,1); ax2 = ax1.twinx();
ax1.bar(tempP.index.tolist(), tempP.values, color='blue')
ax2.plot(tempT.index.tolist(), tempT.values, color='red')
ax1.set_ylabel('Precipitation [mm]', fontsize=10)
ax2.set_ylabel('Temperature [°C]', fontsize=10) 
#ax1.xaxis.set_major_formatter(DateFormatter("%b")) #this line does not work properly!
plt.show()

1 个答案:

答案 0 :(得分:0)

以下是您遇到的问题的工作代码:

valgrind --tool=memcheck --xtree-memory=full <your_program> <your_args>

说明: As of this StackOverflow answer, DateFormatter uses mdates. 为此,您需要从月份名称中创建一个DatetimeIndex-Array ,然后DateFormatter可以重新设置其格式。

对于计算,我理解您问题的解决方案,例如,我们在每个月内取总和,然后取所有年份中这些总和的平均值。这样,您便可以获得所有年份每月平均的平均降水量。