我生成了一系列日期:
pd.date_range("2001-01-01", "2012-12-31")
如何自动排除闰年日期? 2月29日它们出现的年份?
答案 0 :(得分:1)
看起来.date_range()
没有采用允许用户从列表中排除闰日的参数。但是,您可以自己排除它们并创建一个具有非闰年日期的新DatetimeIndex对象:
>>> import pandas as pd
>>> from calendar import isleap
>>> dates = pd.date_range("2001-01-01", "2012-12-31")
>>> pd.DatetimeIndex(data=(t for t in dates if not isleap(t.year)), freq="D")
DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04',
'2001-01-05', '2001-01-06', '2001-01-07', '2001-01-08',
'2001-01-09', '2001-01-10',
...
'2011-12-22', '2011-12-23', '2011-12-24', '2011-12-25',
'2011-12-26', '2011-12-27', '2011-12-28', '2011-12-29',
'2011-12-30', '2011-12-31'],
dtype='datetime64[ns]', length=3285, freq='D')
答案 1 :(得分:0)
从版本0.19.0
开始,您可以使用DatetimeIndex.is_leap_year
:
rng = pd.date_range("2001-01-01", "2012-12-31")
print (rng)
DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04',
'2001-01-05', '2001-01-06', '2001-01-07', '2001-01-08',
'2001-01-09', '2001-01-10',
...
'2012-12-22', '2012-12-23', '2012-12-24', '2012-12-25',
'2012-12-26', '2012-12-27', '2012-12-28', '2012-12-29',
'2012-12-30', '2012-12-31'],
dtype='datetime64[ns]', length=4383, freq='D')
print (rng.is_leap_year)
[False False False ..., True True True]
print (rng[~rng.is_leap_year])
DatetimeIndex(['2001-01-01', '2001-01-02', '2001-01-03', '2001-01-04',
'2001-01-05', '2001-01-06', '2001-01-07', '2001-01-08',
'2001-01-09', '2001-01-10',
...
'2011-12-22', '2011-12-23', '2011-12-24', '2011-12-25',
'2011-12-26', '2011-12-27', '2011-12-28', '2011-12-29',
'2011-12-30', '2011-12-31'],
dtype='datetime64[ns]', length=3285, freq=None)