我有一长串按照以下方式结构化的数据

Date, Time, Temperature, Moisture, Accumulated precipitation

1/01/2011, 00:00, 23, 50, 2,
1/01/2011, 00:15, 22, 45, 1,
1/01/2011, 00:30, 20, 39, 0,
1/01/2011, 01:00, 25, 34, 0,
1/01/2011, 01:15, 23, 50, 0,
           .
           .
           .
           .
1/01/2011, 23:45, 22, 40, 0,
           .
           .
           .
           .
31/01/2011, 00:00, 23, 45, 0,


如何获得每月31日的变量TemperatureMoisture的每日平均值?

最佳答案

pandas库最擅长的就是这种事情。基本思想是,您可以将数据读入称为DataFrames的对象(有点像Excel工作表),然后可以对它们执行整洁的操作。我从一个temps.csv文件开始,看起来像您的文件:

>>> df = pd.read_csv("temps.csv", index_col=False, parse_dates=[[0,1]], skipinitialspace=True)
>>> df = df.rename(columns={"Date _Time": "Time"})
>>> df = df.set_index("Time")
>>> df
                     Temperature  Moisture  Accumulated precipitation
Time
2011-01-01 00:00:00           23        50                          2
2011-01-01 00:15:00           22        45                          1
2011-01-01 00:30:00           20        39                          0
2011-01-01 01:00:00           25        34                          0
2011-01-01 01:15:00           23        50                          0
2011-01-01 23:45:00           22        40                          0
2011-01-02 00:00:00          123       250                         32
2011-01-02 00:15:00          122       245                         31
2011-01-02 00:30:00          120       239                         30
2011-01-02 01:00:00          125       234                         30
2011-01-02 01:15:00          123       250                         30
2011-01-02 23:45:00          122       240                         30


框架形状良好后,我们可以轻松地重新采样(默认为均值):

>>> df.resample("D")
            Temperature  Moisture  Accumulated precipitation
Time
2011-01-01         22.5        43                        0.5
2011-01-02        122.5       243                       30.5


或获得最大或最小:

>>> df.resample("D", how="max")
            Temperature  Moisture  Accumulated precipitation
Time
2011-01-01           25        50                          2
2011-01-02          125       250                         32
>>> df.resample("D", how="min")
            Temperature  Moisture  Accumulated precipitation
Time
2011-01-01           20        34                          0
2011-01-02          120       234                         30


等等。请注意,这只是每天记录的数据点的粗略平均值:如果您想以不同的方式重新采样以考虑两次测量之间的不同距离,这也很容易。如果您打算使用Python进行数据处理,那么绝对值得阅读10 minute overview来查看它是否有帮助。

关于python - 获取每月数据库的每日平均值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19191080/

10-15 12:45
查看更多