Python Pandas系列:获取datetime片段或范围中缺少的所有日期
给定Python Pandas系列:获取datetime片段或范围中缺少的所有日期,python,pandas,python-datetime,Python,Pandas,Python Datetime,给定Pandas系列和datetime片段或日期范围,如何从datetime片段或范围中获取系列中的所有日期 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_
Pandas
系列和datetime
片段或日期范围,如何从datetime
片段或范围中获取系列中的所有日期
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']
返回已排序的集合差异:
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.14.1
中,我没有得到期望的结果,实际上我使用rng.diff(s.index)得到了rng
相同结果的日期范围。format()
必须是0.14.1
s.index
是字符串的索引。您需要将其转换为DatetimeIndex
。您是否正在调用pd.to_datetime
,如rng.difference(pd.to_datetime(s.index)).tolist()
?(我使用的是0.15.1版,但希望这不重要。)在0.20.3版中使用减号会引发ValueError:无法添加长度不等的索引。我使用rng.difference(pd.to_datetime(s.index))解决了这个问题。