2014-01-07 21 views
4

我想用大熊貓來計算每日氣候。我的代碼是:使用熊貓python計算每日氣候

import pandas as pd 

dates  = pd.date_range('1950-01-01', '1953-12-31', freq='D') 
rand_data = [int(1000*random.random()) for i in xrange(len(dates))] 
cum_data = pd.Series(rand_data, index=dates) 
cum_data.to_csv('test.csv', sep="\t") 

cum_data是包含從1950年1月1日每天日期12月31日1953年,我想創建長度365的新載體包含rand_data爲1月1日的平均的第一個元素的數據幀對於1950年,1951年,1952年和1953年等等第二個元素...

任何建議如何使用熊貓來做到這一點?

回答

5

可以GROUPBY年的一天,在計算平均值爲這些羣體:

cum_data.groupby(cum_data.index.dayofyear).mean() 

但是,你有知道的閏年。這會導致這種方法的問題。作爲替代,您還可以按月份和日期分組:

In [13]: cum_data.groupby([cum_data.index.month, cum_data.index.day]).mean() 
Out[13]: 
1 1  462.25 
    2  631.00 
    3  615.50 
    4  496.00 
... 
12 28 378.25 
    29 427.75 
    30 528.50 
    31 678.50 
Length: 366, dtype: float64 
+0

謝謝!這工作完美 – user308827

1

@joris。謝謝。你的答案正是我用熊貓計算日常氣候所需要的,但是你沒有完成最後一步。將月份,日期索引重新映射回所有年份(包括閏年,即1至366)的一年中的某一天。因此,我認爲我會爲其他用戶分享我的解決方案。 1950年到1953年是一年閏年的4年,1952年。注意,因爲使用了隨機值,所以每次運行都會給出不同的結果。

... 
from datetime import date 
doy = [] 
doy_mean = [] 
doy_size = [] 
for name, group in cum_data.groupby([cum_data.index.month, cum_data.index.day]): 
    (mo, dy) = name 
    # Note: can use any leap year here. 
    yrday = (date(1952, mo, dy)).timetuple().tm_yday 
    doy.append(yrday) 
    doy_mean.append(group.mean()) 
    doy_size.append(group.count()) 
    # Note: useful climatology stats are also available via group.describe() returned as dict 
    #desc = group.describe() 
    # desc["mean"], desc["min"], desc["max"], std,quartiles, etc. 

# we lose the counts here. 
new_cum_data = pd.Series(doy_mean, index=doy) 
print new_cum_data.ix[366] 
>> 634.5 

pd_dict = {} 
pd_dict["mean"] = doy_mean 
pd_dict["size"] = doy_size 
cum_data_df = pd.DataFrame(data=pd_dict, index=doy) 

print cum_data_df.ix[366] 
>> mean 634.5 
>> size  4.0 
>> Name: 366, dtype: float64 
# and just to check Feb 29 
print cum_data_df.ix[60] 
>> mean 343 
>> size  1 
>> Name: 60, dtype: float64