2014-12-04 112 views
0

丟失所有日期給出一個Pandas系列及datetime片或範圍的日期,我怎樣才能從datetime片或範圍都在series所有日期?熊貓系列:從日期時間切片或範圍

Ex: 
     #my date time slice/ date_range 
     st = datetime.datetime(2014, 8, 31, 0, 0) 
     en = datetime.datetime(2014, 9, 7, 0, 0) 
     date_slice = slice(st,en) 
     rng = pd.date_range('08-31-2014', periods=8, freq='D') 

     #my series 
     s = pd.Series({'09-01-2014': 1, 
         '09-02-2014': 1, 
         '09-03-2014': np.nan, 
         '09-04-2014': 1, 
         '09-06-2014': 1}) 

在這個例子中,我想在strdatetime格式

['08-31-2014', '09-05-2014' , '09-07-2014'] 

回答

2

DatetimeIndex.difference返回日期的數組返回有序集合的區別:

In [573]: (rng.difference(pd.to_datetime(s.index))).format() 
Out[573]: ['2014-08-31', '2014-09-05', '2014-09-07'] 

In [598]: (rng.difference(pd.to_datetime(s.index))).format(formatter=lambda x: x.strftime('%m-%d-%Y')) 
Out[598]: ['08-31-2014', '09-05-2014', '09-07-2014'] 
+0

什麼版本的熊貓是你使用?也許這是固定在更新的版本,但在'0.14.1'我沒有得到期望的結果,我實際上從'rng'獲得日期範圍 – pyCthon 2014-12-04 23:06:44

+0

使用'rng.diff(s.index)相同的結果。 format()'必須是具有'0.14.1'的錯誤。 – pyCthon 2014-12-04 23:10:04

+0

's.index'是一個字符串索引。您需要將其轉換爲'DatetimeIndex'。你是否在調用'pd.to_datetime',如'rng.difference(pd.to_datetime(s.index))。tolist()'? (我正在使用版本0.15.1,但希望沒關係。) – unutbu 2014-12-04 23:14:43