Skip to content

Commit eae133d

Browse files
committed
fixups
1 parent 7c76b3e commit eae133d

File tree

7 files changed

+29
-82
lines changed

7 files changed

+29
-82
lines changed

pandas/core/arrays/datetimelike.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -297,8 +297,6 @@ class TimelikeOps(object):
297297
)
298298

299299
def _round(self, freq, mode, ambiguous, nonexistent):
300-
from pandas.core.indexes.datetimelike import _ensure_datetimelike_to_i8
301-
302300
# round the local times
303301
values = _ensure_datetimelike_to_i8(self)
304302
result = round_nsint64(values, mode, freq)
@@ -335,7 +333,6 @@ class DatetimeLikeArrayMixin(AttributesMixin,
335333
Assumes that __new__/__init__ defines:
336334
_data
337335
_freq
338-
_scalar_type : {Timestamp, Timedelta, Period}
339336
340337
and that the inheriting class has methods:
341338
_generate_range
@@ -476,10 +473,9 @@ def __setitem__(
476473
# https://mypy.readthedocs.io/en/latest/generics.html
477474

478475
# n.b. This is moved from PeriodArray with the following changes
479-
# 1. added is_slice check (bug on master)
480-
# 2. changed dedicated ctor (period_array) to _from_sequence
481-
# 3. Changed freq checking to use `_check_compatible_with`
482-
# 4. Handle `value=iNaT` (may be able to revert. Check internals.)
476+
# 1. changed dedicated ctor (period_array) to _from_sequence
477+
# 2. Changed freq checking to use `_check_compatible_with`
478+
# 3. Handle `value=iNaT` (may be able to revert. Check internals.)
483479
if is_list_like(value):
484480
is_slice = isinstance(key, slice)
485481
if (not is_slice

pandas/core/arrays/datetimes.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,6 @@ class DatetimeArrayMixin(dtl.DatetimeLikeArrayMixin,
199199
# Constructors
200200

201201
_attributes = ["freq", "tz"]
202-
_tz = None
203202
_freq = None
204203

205204
@classmethod
@@ -222,7 +221,6 @@ def _simple_new(cls, values, freq=None, tz=None):
222221
result._freq = freq
223222
tz = timezones.maybe_get_tz(tz)
224223
if tz:
225-
result._tz = timezones.tz_standardize(tz)
226224
result._dtype = DatetimeTZDtype('ns', tz)
227225
else:
228226
result._dtype = values.dtype # M8[ns]
@@ -392,7 +390,7 @@ def tz(self):
392390
Return timezone.
393391
"""
394392
# GH 18595
395-
return self._tz
393+
return getattr(self.dtype, 'tz', None)
396394

397395
@tz.setter
398396
def tz(self, value):

pandas/core/arrays/period.py

+1-45
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from pandas.core.dtypes.common import (
1818
_TD_DTYPE, ensure_object, is_array_like, is_datetime64_dtype,
1919
is_datetime64_ns_dtype, is_datetime64tz_dtype, is_float_dtype,
20-
is_list_like, is_period_dtype, pandas_dtype)
20+
is_period_dtype, pandas_dtype)
2121
from pandas.core.dtypes.dtypes import PeriodDtype
2222
from pandas.core.dtypes.generic import ABCIndexClass, ABCPeriodIndex, ABCSeries
2323
from pandas.core.dtypes.missing import isna, notna
@@ -362,50 +362,6 @@ def _formatter(self, boxed=False):
362362
return str
363363
return "'{}'".format
364364

365-
def __setitem__(
366-
self,
367-
key, # type: Union[int, Sequence[int], Sequence[bool], slice]
368-
value # type: Union[NaTType, Period, Sequence[Period]]
369-
):
370-
# type: (...) -> None
371-
# n.b. the type on `value` is a bit too restrictive.
372-
# we also accept a sequence of stuff coercible to a PeriodArray
373-
# by period_array, which includes things like ndarray[object],
374-
# ndarray[datetime64ns]. I think ndarray[int] / ndarray[str] won't
375-
# work, since the freq can't be inferred.
376-
if is_list_like(value):
377-
is_slice = isinstance(key, slice)
378-
if (not is_slice
379-
and len(key) != len(value)
380-
and not com.is_bool_indexer(key)):
381-
msg = ("shape mismatch: value array of length '{}' does not "
382-
"match indexing result of length '{}'.")
383-
raise ValueError(msg.format(len(key), len(value)))
384-
if not is_slice and len(key) == 0:
385-
return
386-
387-
value = period_array(value)
388-
389-
if self.freqstr != value.freqstr:
390-
msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr)
391-
raise IncompatibleFrequency(msg)
392-
393-
value = value.asi8
394-
elif isinstance(value, Period):
395-
396-
if self.freqstr != value.freqstr:
397-
msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, value.freqstr)
398-
raise IncompatibleFrequency(msg)
399-
400-
value = value.ordinal
401-
elif isna(value):
402-
value = iNaT
403-
else:
404-
msg = ("'value' should be a 'Period', 'NaT', or array of those. "
405-
"Got '{}' instead.".format(type(value).__name__))
406-
raise TypeError(msg)
407-
self._data[key] = value
408-
409365
@Appender(dtl.DatetimeLikeArrayMixin._validate_fill_value.__doc__)
410366
def _validate_fill_value(self, fill_value):
411367
if isna(fill_value):

pandas/core/base.py

+5-10
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from pandas.util._validators import validate_bool_kwarg
1616

1717
from pandas.core.dtypes.common import (
18-
is_datetime64_dtype, is_datetimelike, is_extension_array_dtype,
18+
is_datetime64tz_dtype, is_datetimelike, is_extension_array_dtype,
1919
is_extension_type, is_list_like, is_object_dtype, is_scalar)
2020
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
2121
from pandas.core.dtypes.missing import isna
@@ -895,15 +895,10 @@ def to_numpy(self):
895895
>>> ser.to_numpy()
896896
array(['a', 'b', 'a'], dtype=object)
897897
"""
898-
if is_extension_array_dtype(self.dtype):
899-
return np.asarray(self._values)
900-
elif is_datetime64_dtype(self.dtype):
901-
# This secondary `asarray` may be unavoidable, as long as
902-
# we have
903-
# 1. DatetimeArray-backed Index
904-
# 2. `M8[ns]` dtype for tz-naive, DatetimeTZDtype for tz-aware.
905-
return np.asarray(self._values)
906-
return self._values
898+
if is_datetime64tz_dtype(self.dtype):
899+
# Ensure that timezones are preserved.
900+
return np.asarray(self._values.astype(object))
901+
return np.asarray(self._values)
907902

908903
@property
909904
def _ndarray_values(self):

pandas/core/dtypes/concat.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -436,8 +436,8 @@ def _concat_datetime(to_concat, axis=0, typs=None):
436436
return _concat_datetimetz(to_concat)
437437

438438
elif 'timedelta' in typs:
439-
to_concat = [x.astype(np.int64, copy=False) for x in to_concat]
440-
return _concatenate_2d(to_concat, axis=axis).view(_TD_DTYPE)
439+
return _concatenate_2d([x.view(np.int64) for x in to_concat],
440+
axis=axis).view(_TD_DTYPE)
441441

442442
elif any(typ.startswith('period') for typ in typs):
443443
assert len(typs) == 1
@@ -455,9 +455,7 @@ def _convert_datetimelike_to_object(x):
455455
x = np.asarray(x.astype(object))
456456
else:
457457
shape = x.shape
458-
x = tslib.ints_to_pydatetime(x.astype(np.int64,
459-
copy=False).ravel(),
460-
box="timestamp")
458+
x = tslib.ints_to_pydatetime(x.view(np.int64).ravel(), box=True)
461459
x = x.reshape(shape)
462460

463461
elif x.dtype == _TD_DTYPE:

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9658,7 +9658,7 @@ def describe_categorical_1d(data):
96589658
if is_datetime64_any_dtype(data):
96599659
tz = data.dt.tz
96609660
# astype for ndarray / datetimearray compat.
9661-
asint = data.dropna()._values.astype('i8', copy=False)
9661+
asint = data.dropna().values.view('i8')
96629662
top = Timestamp(top)
96639663
if top.tzinfo is not None and tz is not None:
96649664
# Don't tz_localize(None) if key is already tz-aware

pandas/tests/test_base.py

+15-11
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@
1616
from pandas import (Series, Index, DatetimeIndex, TimedeltaIndex,
1717
PeriodIndex, Timedelta, IntervalIndex, Interval,
1818
CategoricalIndex, Timestamp)
19-
from pandas.core.arrays import DatetimeArrayMixin as DatetimeArray
19+
from pandas.core.arrays import (
20+
DatetimeArrayMixin as DatetimeArray,
21+
TimedeltaArrayMixin as TimedeltaArray,
22+
)
2023
from pandas.compat import StringIO, PYPY, long
2124
from pandas.compat.numpy import np_array_datetime64_compat
2225
from pandas.core.accessor import PandasDelegate
@@ -1314,16 +1317,17 @@ def test_array_multiindex_raises():
13141317
(DatetimeArray(np.array(['2000', '2001'], dtype='M8[ns]')),
13151318
np.array(['2000', '2001'], dtype='M8[ns]')),
13161319
1317-
# tz-aware datetime
1318-
# XXX: On master, np.asarray(Series[datetime64[ns, tz]]) is
1319-
# an ndarray[datetime64[ns]] (normalized to UTC and tz dropped).
1320-
# Do we want to change that?
1321-
# Or do we want `.to_numpy()` to be inconsistent with asarray? (no!)
1322-
pytest.param(
1323-
DatetimeArray(np.array(['2000', '2000'], dtype='M8[ns]'),
1324-
tz='US/Central'),
1325-
np.array([pd.Timestamp("2000", tz="US/Central")] * 2),
1326-
marks=pytest.mark.xfail(reason="np.asarray", strict=True))
1320+
# tz-aware stays tz`-aware
1321+
(DatetimeArray(np.array(['2000-01-01T06:00:00',
1322+
'2000-01-02T06:00:00'],
1323+
dtype='M8[ns]'),
1324+
tz='US/Central'),
1325+
np.array([pd.Timestamp('2000-01-01', tz='US/Central'),
1326+
pd.Timestamp('2000-01-02', tz='US/Central')])),
1327+
1328+
# Timedelta
1329+
(TimedeltaArray([0, 3600000000000], freq='H'),
1330+
np.array([0, 3600000000000], dtype='m8[ns]')),
13271331
])
13281332
@pytest.mark.parametrize('box', [pd.Series, pd.Index])
13291333
def test_to_numpy(array, expected, box):

0 commit comments

Comments
 (0)