熊猫系列:从日期时间片或范围中删除所有日期

时间:2014-12-04 21:37:24

标签: python pandas python-datetime

鉴于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']

1 个答案:

答案 0 :(得分: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']