Domanda

I have the following data (generated through another script I have created),

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

The next step is that I want to sort this data so that it will be presented in a .csv like this:

Month, Mean
01/1951, 0.5 
02/1951, 0.1
etc.....

Is there an easy way to do this?

È stato utile?

Soluzione

If you install pandas, then you can load the CSV into a pandas DataFrame using

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

and compute the means for each month using

In [53]: result = df.resample('M', how='mean'); result

Out[53]: 
                 HAD
Date                
1951-01-31  0.009546

and save the CSV to a file using:

In [49]: result.to_csv('/tmp/out')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top