Skip to content

Commit d8826bf

Browse files
jbrockmendelJustinZhengBC
authored andcommitted
CLN: datetimelike arrays: isort, small reorg (pandas-dev#23587)
1 parent d4be020 commit d8826bf

13 files changed

+211
-229
lines changed

pandas/core/arrays/datetimelike.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,12 @@ def asi8(self):
124124
# do not cache or you'll create a memory leak
125125
return self._data.view('i8')
126126

127-
# ------------------------------------------------------------------
128-
# Array-like Methods
127+
# ----------------------------------------------------------------
128+
# Array-Like / EA-Interface Methods
129+
130+
@property
131+
def nbytes(self):
132+
return self._data.nbytes
129133

130134
@property
131135
def shape(self):

pandas/core/arrays/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ def _resolution(self):
385385
return libresolution.resolution(self.asi8, self.tz)
386386

387387
# ----------------------------------------------------------------
388-
# Array-like Methods
388+
# Array-Like / EA-Interface Methods
389389

390390
def __array__(self, dtype=None):
391391
if is_object_dtype(dtype):

pandas/core/arrays/period.py

+52-54
Original file line numberDiff line numberDiff line change
@@ -272,10 +272,6 @@ def _concat_same_type(cls, to_concat):
272272

273273
# --------------------------------------------------------------------
274274
# Data / Attributes
275-
@property
276-
def nbytes(self):
277-
# TODO(DatetimeArray): remove
278-
return self._data.nbytes
279275

280276
@cache_readonly
281277
def dtype(self):
@@ -286,10 +282,6 @@ def _ndarray_values(self):
286282
# Ordinals
287283
return self._data
288284

289-
@property
290-
def asi8(self):
291-
return self._data
292-
293285
@property
294286
def freq(self):
295287
"""Return the frequency object for this PeriodArray."""
@@ -330,6 +322,50 @@ def start_time(self):
330322
def end_time(self):
331323
return self.to_timestamp(how='end')
332324

325+
def to_timestamp(self, freq=None, how='start'):
326+
"""
327+
Cast to DatetimeArray/Index.
328+
329+
Parameters
330+
----------
331+
freq : string or DateOffset, optional
332+
Target frequency. The default is 'D' for week or longer,
333+
'S' otherwise
334+
how : {'s', 'e', 'start', 'end'}
335+
336+
Returns
337+
-------
338+
DatetimeArray/Index
339+
"""
340+
from pandas.core.arrays import DatetimeArrayMixin
341+
342+
how = libperiod._validate_end_alias(how)
343+
344+
end = how == 'E'
345+
if end:
346+
if freq == 'B':
347+
# roll forward to ensure we land on B date
348+
adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
349+
return self.to_timestamp(how='start') + adjust
350+
else:
351+
adjust = Timedelta(1, 'ns')
352+
return (self + self.freq).to_timestamp(how='start') - adjust
353+
354+
if freq is None:
355+
base, mult = frequencies.get_freq_code(self.freq)
356+
freq = frequencies.get_to_timestamp_base(base)
357+
else:
358+
freq = Period._maybe_convert_freq(freq)
359+
360+
base, mult = frequencies.get_freq_code(freq)
361+
new_data = self.asfreq(freq, how=how)
362+
363+
new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
364+
return DatetimeArrayMixin(new_data, freq='infer')
365+
366+
# --------------------------------------------------------------------
367+
# Array-like / EA-Interface Methods
368+
333369
def __repr__(self):
334370
return '<{}>\n{}\nLength: {}, dtype: {}'.format(
335371
self.__class__.__name__,
@@ -456,6 +492,8 @@ def value_counts(self, dropna=False):
456492
name=result.index.name)
457493
return Series(result.values, index=index, name=result.name)
458494

495+
# --------------------------------------------------------------------
496+
459497
def shift(self, periods=1):
460498
"""
461499
Shift values by desired number.
@@ -567,49 +605,9 @@ def asfreq(self, freq=None, how='E'):
567605

568606
return type(self)(new_data, freq=freq)
569607

570-
def to_timestamp(self, freq=None, how='start'):
571-
"""
572-
Cast to DatetimeArray/Index
573-
574-
Parameters
575-
----------
576-
freq : string or DateOffset, optional
577-
Target frequency. The default is 'D' for week or longer,
578-
'S' otherwise
579-
how : {'s', 'e', 'start', 'end'}
580-
581-
Returns
582-
-------
583-
DatetimeArray/Index
584-
"""
585-
from pandas.core.arrays import DatetimeArrayMixin
586-
587-
how = libperiod._validate_end_alias(how)
588-
589-
end = how == 'E'
590-
if end:
591-
if freq == 'B':
592-
# roll forward to ensure we land on B date
593-
adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
594-
return self.to_timestamp(how='start') + adjust
595-
else:
596-
adjust = Timedelta(1, 'ns')
597-
return (self + self.freq).to_timestamp(how='start') - adjust
598-
599-
if freq is None:
600-
base, mult = frequencies.get_freq_code(self.freq)
601-
freq = frequencies.get_to_timestamp_base(base)
602-
else:
603-
freq = Period._maybe_convert_freq(freq)
604-
605-
base, mult = frequencies.get_freq_code(freq)
606-
new_data = self.asfreq(freq, how=how)
607-
608-
new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
609-
return DatetimeArrayMixin(new_data, freq='infer')
610-
611608
# ------------------------------------------------------------------
612609
# Formatting
610+
613611
def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs):
614612
""" actually format my specific types """
615613
# TODO(DatetimeArray): remove
@@ -630,9 +628,13 @@ def _format_native_types(self, na_rep=u'NaT', date_format=None, **kwargs):
630628
values = np.array([formatter(dt) for dt in values])
631629
return values
632630

631+
# Delegation...
632+
def strftime(self, date_format):
633+
return self._format_native_types(date_format=date_format)
634+
633635
def repeat(self, repeats, *args, **kwargs):
634636
"""
635-
Repeat elements of a Categorical.
637+
Repeat elements of a PeriodArray.
636638
637639
See also
638640
--------
@@ -643,10 +645,6 @@ def repeat(self, repeats, *args, **kwargs):
643645
values = self._data.repeat(repeats)
644646
return type(self)(values, self.freq)
645647

646-
# Delegation...
647-
def strftime(self, date_format):
648-
return self._format_native_types(date_format=date_format)
649-
650648
def astype(self, dtype, copy=True):
651649
# TODO: Figure out something better here...
652650
# We have DatetimeLikeArrayMixin ->

pandas/core/arrays/timedeltas.py

+19-7
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,9 @@ def _generate_range(cls, start, end, periods, freq, closed=None):
190190

191191
return cls._simple_new(index, freq=freq)
192192

193+
# ----------------------------------------------------------------
194+
# Array-Like / EA-Interface Methods
195+
193196
# ----------------------------------------------------------------
194197
# Arithmetic Methods
195198

@@ -412,20 +415,25 @@ def sequence_to_td64ns(data, copy=False, unit="ns", errors="raise"):
412415
array : list-like
413416
copy : bool, default False
414417
unit : str, default "ns"
418+
The timedelta unit to treat integers as multiples of.
415419
errors : {"raise", "coerce", "ignore"}, default "raise"
420+
How to handle elements that cannot be converted to timedelta64[ns].
421+
See ``pandas.to_timedelta`` for details.
416422
417423
Returns
418424
-------
419-
ndarray[timedelta64[ns]]
425+
converted : numpy.ndarray
426+
The sequence converted to a numpy array with dtype ``timedelta64[ns]``.
420427
inferred_freq : Tick or None
428+
The inferred frequency of the sequence.
421429
422430
Raises
423431
------
424-
ValueError : data cannot be converted to timedelta64[ns]
432+
ValueError : Data cannot be converted to timedelta64[ns].
425433
426434
Notes
427435
-----
428-
Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause
436+
Unlike `pandas.to_timedelta`, if setting ``errors=ignore`` will not cause
429437
errors to be ignored; they are caught and subsequently ignored at a
430438
higher level.
431439
"""
@@ -497,12 +505,13 @@ def ints_to_td64ns(data, unit="ns"):
497505
498506
Parameters
499507
----------
500-
data : np.ndarray with integer-dtype
508+
data : numpy.ndarray with integer-dtype
501509
unit : str, default "ns"
510+
The timedelta unit to treat integers as multiples of.
502511
503512
Returns
504513
-------
505-
ndarray[timedelta64[ns]]
514+
numpy.ndarray : timedelta64[ns] array converted from data
506515
bool : whether a copy was made
507516
"""
508517
copy_made = False
@@ -538,15 +547,18 @@ def objects_to_td64ns(data, unit="ns", errors="raise"):
538547
----------
539548
data : ndarray or Index
540549
unit : str, default "ns"
550+
The timedelta unit to treat integers as multiples of.
541551
errors : {"raise", "coerce", "ignore"}, default "raise"
552+
How to handle elements that cannot be converted to timedelta64[ns].
553+
See ``pandas.to_timedelta`` for details.
542554
543555
Returns
544556
-------
545-
ndarray[timedelta64[ns]]
557+
numpy.ndarray : timedelta64[ns] array converted from data
546558
547559
Raises
548560
------
549-
ValueError : data cannot be converted to timedelta64[ns]
561+
ValueError : Data cannot be converted to timedelta64[ns].
550562
551563
Notes
552564
-----

pandas/core/indexes/datetimelike.py

+16-28
Original file line numberDiff line numberDiff line change
@@ -4,44 +4,32 @@
44
"""
55
import warnings
66

7-
from pandas import compat
8-
from pandas.compat.numpy import function as nv
9-
from pandas.core.tools.timedeltas import to_timedelta
10-
117
import numpy as np
128

13-
from pandas._libs import lib, iNaT, NaT
14-
from pandas._libs.tslibs.timestamps import round_nsint64, RoundTo
9+
from pandas._libs import NaT, iNaT, lib
10+
from pandas._libs.tslibs.timestamps import RoundTo, round_nsint64
11+
import pandas.compat as compat
12+
from pandas.compat.numpy import function as nv
13+
from pandas.util._decorators import Appender, cache_readonly
1514

1615
from pandas.core.dtypes.common import (
17-
ensure_int64,
18-
is_dtype_equal,
19-
is_float,
20-
is_integer,
21-
is_list_like,
22-
is_scalar,
23-
is_bool_dtype,
24-
is_period_dtype,
25-
is_categorical_dtype,
26-
is_datetime_or_timedelta_dtype,
27-
is_float_dtype,
28-
is_integer_dtype,
29-
is_object_dtype,
30-
is_string_dtype)
31-
from pandas.core.dtypes.generic import (
32-
ABCIndex, ABCSeries, ABCIndexClass)
16+
ensure_int64, is_bool_dtype, is_categorical_dtype,
17+
is_datetime_or_timedelta_dtype, is_dtype_equal, is_float, is_float_dtype,
18+
is_integer, is_integer_dtype, is_list_like, is_object_dtype,
19+
is_period_dtype, is_scalar, is_string_dtype)
20+
import pandas.core.dtypes.concat as _concat
21+
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries
3322
from pandas.core.dtypes.missing import isna
34-
from pandas.core import common as com, algorithms, ops
35-
36-
import pandas.io.formats.printing as printing
3723

24+
from pandas.core import algorithms, common as com, ops
3825
from pandas.core.arrays import PeriodArray
3926
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
27+
import pandas.core.indexes.base as ibase
4028
from pandas.core.indexes.base import Index, _index_shared_docs
41-
from pandas.util._decorators import Appender, cache_readonly
42-
import pandas.core.dtypes.concat as _concat
29+
from pandas.core.tools.timedeltas import to_timedelta
30+
31+
import pandas.io.formats.printing as printing
4332

44-
import pandas.core.indexes.base as ibase
4533
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
4634

4735

0 commit comments

Comments
 (0)