鉴于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})
在此示例中,我想以str
或datetime
格式返回日期数组
['08-31-2014', '09-05-2014' , '09-07-2014']
答案 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']