I generate a series of dates like this:
pd.date_range("2001-01-01", "2012-12-31")
我该如何自动排除闰年日期?在闰年中出现的2月29日?
看起来.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')
从版本 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)