我有一个pandas.DatetimeIndex
间隔['2018-01-01', '2018-01-04')
(包括开始,不包括结束)和freq=1D
:
>>> index = pd.DatetimeIndex(start='2018-01-01',
end='2018-01-04',
freq='1D',
closed='left')
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03'],
dtype='datetime64[ns]',
freq='D')
如何end='2018-01-04'
再次获得正确的open属性?我需要带有时间戳范围的数据库查询。
index.end
index[-1]
退货 '2018-01-03'
index[-1] + index.freq
在这种情况下有效,但是对于 freq='2D'
没有办法,因为在构造对象之后这些信息会丢失。在创建时,间隔将展开为结果序列:
pandas/core/indexes/datetimes.py
:
class DatetimeIndex(<...>):
<...>
@classmethod
def _generate(cls, start, end, periods, name, freq,
tz=None, normalize=False, ambiguous='raise', closed=None):
<...>
index = tools.to_datetime(np.linspace(start.value,
end.value, periods),
utc=True)
<...>
if not left_closed and len(index) and index[0] == start:
index = index[1:]
if not right_closed and len(index) and index[-1] == end:
index = index[:-1]
index = cls._simple_new(index, name=name, freq=freq, tz=tz)
return index
无论是closed
信息保存在任何地方,所以你甚至不能从第一/最后一个点,并一步来推断。
您可以继承DatetimeIndex
并保存此信息。请注意,这是一个不可变的类型,因此您需要覆盖__new__
而不是__init__
:
import inspect, collections
class SiDatetimeIndex(pd.DatetimeIndex):
_Interval = collections.namedtuple('Interval',
('start','end','freq','closed'))
#add 'interval' to dir(): DatetimeIndex inherits pandas.core.accessor.DirNamesMixin
_accessors = pd.DatetimeIndex._accessors | frozenset(('interval',))
def __new__(cls, *args, **kwargs):
base_new = super(SiDatetimeIndex,cls).__new__
callargs = inspect.getcallargs(base_new,cls,*args,**kwargs)
result = base_new(**callargs)
result.interval = cls._Interval._make(callargs[a] for a in cls._Interval._fields)
return result
In [31]: index = SiDatetimeIndex(start='2018-01-01',
...: end='2018-01-04',
...: freq='1D',
...: closed='left')
In [38]: index.interval
Out[38]: Interval(start='2018-01-01', end='2018-01-04', freq='1D', closed='left')
尽管不要奢望所有pandas
方法(包括类中的继承方法)现在都可以神奇地开始创建您的重写类。为此,您需要在pandas
这些方法使用的已加载模块中替换对基类的实时引用。或者,您可以只替换原始文档__new__
-则无需替换参考。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句