使用Python Pandas每日平均使用每日数据

DJV*_*DJV 5 python time-series pandas

我是Python用户,但在使用熊猫方面是新手.我希望更多地使用它,因为我正在处理大量的时间序列,并且我听说用熊猫修改它们要容易得多.我已经阅读了一些教程,但它们还没有意义.希望你能帮我一个例子.

我有一个包含四列的文本文件:年,月,日和雪深.这是1979年至2009年30年的每日数据.我想用熊猫技术计算360(30个月X 12个月)个月月平均值(即分离1979年1月,1979年2月,2009年12月和平均每个的所有值).有人可以帮我解决一些示例代码吗?

谢谢.

1979    1   1   3
1979    1   2   3
1979    1   3   3
1979    1   4   3
1979    1   5   3
1979    1   6   3
1979    1   7   4
1979    1   8   5
1979    1   9   7
1979    1   10  8
1979    1   11  16
1979    1   12  16
1979    1   13  16
1979    1   14  18
1979    1   15  18
1979    1   16  18
1979    1   17  18
1979    1   18  20
1979    1   19  20
1979    1   20  20
1979    1   21  20
1979    1   22  20
1979    1   23  18
1979    1   24  18
1979    1   25  18
1979    1   26  18
1979    1   27  18
1979    1   28  18
1979    1   29  18
1979    1   30  18
1979    1   31  19
1979    2   1   19
1979    2   2   19
1979    2   3   19
1979    2   4   19
1979    2   5   19
1979    2   6   22
1979    2   7   24
1979    2   8   27
1979    2   9   29
1979    2   10  32
1979    2   11  32
1979    2   12  32
1979    2   13  32
1979    2   14  33
1979    2   15  33
1979    2   16  33
1979    2   17  34
1979    2   18  36
1979    2   19  36
1979    2   20  36
1979    2   21  36
1979    2   22  36
1979    2   23  36
1979    2   24  31
1979    2   25  29
1979    2   26  27
1979    2   27  27
1979    2   28  27
Run Code Online (Sandbox Code Playgroud)

Zac*_*oss 6

您需要按年份和月份对数据进行分组,然后计算每个组的平均值.伪代码:

import numpy as np
import pandas as pd

# Read in your file as a pandas.DataFrame
# using 'any number of whitespace' as the seperator
df = pd.read_csv("snow.txt", sep='\s*', names=["year", "month", "day", "snow_depth"])

# Show the first 5 rows of the DataFrame
print df.head()

# Group data first by year, then by month
g = df.groupby(["year", "month"])

# For each group, calculate the average of only the snow_depth column
monthly_averages = g.aggregate({"snow_depth":np.mean})
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Pandas中的split-apply-combine方法,请阅读此处.

一个数据帧是:

"具有标记轴(行和列)的二维大小可变,可能异构的表格数据结构."

出于您的目的,numpy ndarray和a 之间的区别并DataFrame不太重要,但DataFrames有一系列功能可以让您的生活更轻松,所以我建议您对它们进行一些阅读.