我有以下数据(通过我创建的另一个脚本生成),
Date,HAD
01/01/1951,1
02/01/1951,-0.13161201
03/01/1951,-0.271796132
04/01/1951,-0.258977158
05/01/1951,-0.198823057
06/01/1951,0.167794502
07/01/1951,0.046093808
08/01/1951,-0.122396694
09/01/1951,-0.121824587
10/01/1951,-0.013002463
下一步是我要对这些数据进行排序,使其以.csv呈现,如下所示:
Month, Mean
01/1951, 0.5
02/1951, 0.1
etc.....
有一种简单的方法吗?
答案 0 :(得分:1)
如果您安装pandas,则可以使用
将CSV加载到pandas DataFrame中In [51]: df = pd.read_csv('data', parse_dates=[0], index_col=[0], dayfirst=True); df
Out[52]:
HAD
Date
1951-01-01 1.000000
1951-01-02 -0.131612
1951-01-03 -0.271796
1951-01-04 -0.258977
1951-01-05 -0.198823
1951-01-06 0.167795
1951-01-07 0.046094
1951-01-08 -0.122397
1951-01-09 -0.121825
1951-01-10 -0.013002
并使用
计算每个月的均值In [53]: result = df.resample('M', how='mean'); result
Out[53]:
HAD
Date
1951-01-31 0.009546
并使用以下方法将CSV保存到文件中
In [49]: result.to_csv('/tmp/out')