2013-11-22 124 views
1

我是python的新手,並且存在以下問題:Python:通過日期時間索引熊貓系列

我每天都會將測量值導入到pd.series對象中。問題是數據是這樣的,每個月總是有31次測量,無論是1月份還是2月份。如果相應的月份少於31天,那麼超過該月最後一天的那些日期的測量值將設置爲零。但是,一個月內丟失的數據也會設置爲零。四月和五月的數據看起來像這樣。

1990-04-01 25.870 
1990-04-01 26.205 
1990-04-01 12.283 
1990-04-01 19.630 
1990-04-01 19.239 
1990-04-01 23.614 
1990-04-01 40.891 
1990-04-01 41.152 
1990-04-01 35.935 
1990-04-01 25.682 
1990-04-01 21.674 
1990-04-01 15.818 
1990-04-01 11.413 
1990-04-01 16.522 
1990-04-01 33.543 
1990-04-01 28.727 
1990-04-01 18.043 
1990-04-01 10.326 
1990-04-01 19.159 
1990-04-01 21.848 
1990-04-01 35.250 
1990-04-01 39.152 
1990-04-01 31.522 
1990-04-01 23.152 
1990-04-01 13.250 
1990-04-01 20.705 
1990-04-01 27.304 
1990-04-01 24.478 
1990-04-01 33.674 
1990-04-01 32.591 
1990-04-01  0.000 
1990-05-01 40.370 
1990-05-01 41.609 
1990-05-01 47.478 
1990-05-01 40.682 
1990-05-01 42.587 
1990-05-01 38.826 
1990-05-01 35.543 
1990-05-01 30.955 
1990-05-01 23.543 
1990-05-01  7.857 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01  0.000 
1990-05-01 54.133 
1990-05-01 41.114 
1990-05-01 44.739 
1990-05-01 43.848 
1990-05-01 26.739 
1990-05-01 21.318 
1990-05-01 26.750 
1990-05-01 54.864 
1990-05-01 33.000 
1990-05-01 33.304 
1990-05-01 34.304 
1990-05-01 20.886 
1990-05-01 20.250 
1990-05-01 24.804 
1990-05-01 28.091 
Length: 62 

是否有辦法刪除那些不屬於相應月份的條目併爲每一天提供新的時間索引?我需要在一個月內保持零。

+0

我走了一下平底船在這裏,因爲我沒有安裝熊貓,但如果你嘗試s [['1990-04-01','1990-04-02']],會發生什麼? (當然,假設你的系列被稱爲s)。如果它給你一些合理的話,那麼問題現在是一個更加容易理解的問題,可以生成所有有效索引的列表。 – Dave

回答

1

首先,我將與南替換0(象徵丟失數據):

s.replace(0, np.nan, inplace=True) 

一種方法是創建作用於每個組的功能(月):

def f(s_month): 
    date = s_month.index[0] 
    # create the month long range 
    rng = pd.date_range(date, date + pd.offsets.MonthEnd(1), freq='D') 
    # throw away results longer than month length 
    s_month = s_month.iloc[0:len(rng)] 
    # reindex those remaining 
    s_month.index = rng 
    return s_month 

注:這需要你有一個DatetimeIndex,即s.index = pd.to_datetime(s.index)

In [11]: s_month = s.loc['1990-04-01'] 

In [12]: f(s_month) 
Out[12]: 
1990-04-01 25.870 
1990-04-02 26.205 
1990-04-03 12.283 
1990-04-04 19.630 
... 
1990-04-28 24.478 
1990-04-29 33.674 
1990-04-30 32.591 
Freq: D, Name: Value, dtype: float64 

使用此與GROUPBY適用於:

In [13]: res = s.groupby(s.index).apply(f) 

In [14]: res 
Out[14]: 
1990-04-01 1990-04-01 25.870 
      1990-04-02 26.205 
      1990-04-03 12.283 
      1990-04-04 19.630 
... 

糾正多指標:

In [15]: res.index = res.index.droplevel(0) 

In [16]: res 
Out[16]: 
1990-04-01 25.870 
1990-04-02 26.205 
1990-04-03 12.283 
... 
+0

非常感謝 - 這就是我一直在尋找的! – user3018865