Skip to content

Commit 0f93848

Browse files
authored
Merge pull request #81 from pandas-dev/master
Sync Fork from Upstream Repo
2 parents 32bc997 + 8f51c99 commit 0f93848

25 files changed

+122
-179
lines changed

doc/source/whatsnew/v1.1.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ Backwards incompatible API changes
9191
now raise a ``TypeError`` if a not-accepted keyword argument is passed into it.
9292
Previously a ``UnsupportedFunctionCall`` was raised (``AssertionError`` if ``min_count`` passed into :meth:`~DataFrameGroupby.median``) (:issue:`31485`)
9393
- :meth:`DataFrame.at` and :meth:`Series.at` will raise a ``TypeError`` instead of a ``ValueError`` if an incompatible key is passed, and ``KeyError`` if a missing key is passed, matching the behavior of ``.loc[]`` (:issue:`31722`)
94+
- Passing an integer dtype other than ``int64`` to ``np.array(period_index, dtype=...)`` will now raise ``TypeError`` instead of incorrectly using ``int64`` (:issue:`32255`)
95+
-
9496

9597
.. _whatsnew_110.api_breaking.indexing_raises_key_errors:
9698

pandas/_libs/tslibs/timedeltas.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -1167,7 +1167,7 @@ class Timedelta(_Timedelta):
11671167
11681168
Possible values:
11691169
1170-
* 'Y', 'M', 'W', 'D', 'T', 'S', 'L', 'U', or 'N'
1170+
* 'W', 'D', 'T', 'S', 'L', 'U', or 'N'
11711171
* 'days' or 'day'
11721172
* 'hours', 'hour', 'hr', or 'h'
11731173
* 'minutes', 'minute', 'min', or 'm'

pandas/core/arrays/datetimes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -988,7 +988,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise"):
988988
# ----------------------------------------------------------------
989989
# Conversion Methods - Vectorized analogues of Timestamp methods
990990

991-
def to_pydatetime(self):
991+
def to_pydatetime(self) -> np.ndarray:
992992
"""
993993
Return Datetime Array/Index as object ndarray of datetime.datetime
994994
objects.

pandas/core/arrays/period.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,12 @@ def freq(self):
282282
return self.dtype.freq
283283

284284
def __array__(self, dtype=None) -> np.ndarray:
285-
# overriding DatetimelikeArray
285+
if dtype == "i8":
286+
return self.asi8
287+
elif dtype == bool:
288+
return ~self._isnan
289+
290+
# This will raise TypeErorr for non-object dtypes
286291
return np.array(list(self), dtype=object)
287292

288293
def __arrow_array__(self, type=None):

pandas/core/arrays/timedeltas.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -825,7 +825,7 @@ def total_seconds(self):
825825
"""
826826
return self._maybe_mask_results(1e-9 * self.asi8, fill_value=None)
827827

828-
def to_pytimedelta(self):
828+
def to_pytimedelta(self) -> np.ndarray:
829829
"""
830830
Return Timedelta Array/Index as object ndarray of datetime.timedelta
831831
objects.

pandas/core/dtypes/common.py

+2-74
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import numpy as np
99

10-
from pandas._libs import algos, lib
10+
from pandas._libs import algos
1111
from pandas._libs.tslibs import conversion
1212
from pandas._typing import ArrayLike, DtypeObj
1313

@@ -19,14 +19,7 @@
1919
PeriodDtype,
2020
registry,
2121
)
22-
from pandas.core.dtypes.generic import (
23-
ABCCategorical,
24-
ABCDatetimeIndex,
25-
ABCIndexClass,
26-
ABCPeriodArray,
27-
ABCPeriodIndex,
28-
ABCSeries,
29-
)
22+
from pandas.core.dtypes.generic import ABCCategorical, ABCIndexClass
3023
from pandas.core.dtypes.inference import ( # noqa:F401
3124
is_array_like,
3225
is_bool,
@@ -606,71 +599,6 @@ def is_excluded_dtype(dtype) -> bool:
606599
return _is_dtype(arr_or_dtype, condition)
607600

608601

609-
def is_period_arraylike(arr) -> bool:
610-
"""
611-
Check whether an array-like is a periodical array-like or PeriodIndex.
612-
613-
Parameters
614-
----------
615-
arr : array-like
616-
The array-like to check.
617-
618-
Returns
619-
-------
620-
boolean
621-
Whether or not the array-like is a periodical array-like or
622-
PeriodIndex instance.
623-
624-
Examples
625-
--------
626-
>>> is_period_arraylike([1, 2, 3])
627-
False
628-
>>> is_period_arraylike(pd.Index([1, 2, 3]))
629-
False
630-
>>> is_period_arraylike(pd.PeriodIndex(["2017-01-01"], freq="D"))
631-
True
632-
"""
633-
if isinstance(arr, (ABCPeriodIndex, ABCPeriodArray)):
634-
return True
635-
elif isinstance(arr, (np.ndarray, ABCSeries)):
636-
return is_period_dtype(arr.dtype)
637-
return getattr(arr, "inferred_type", None) == "period"
638-
639-
640-
def is_datetime_arraylike(arr) -> bool:
641-
"""
642-
Check whether an array-like is a datetime array-like or DatetimeIndex.
643-
644-
Parameters
645-
----------
646-
arr : array-like
647-
The array-like to check.
648-
649-
Returns
650-
-------
651-
boolean
652-
Whether or not the array-like is a datetime array-like or
653-
DatetimeIndex.
654-
655-
Examples
656-
--------
657-
>>> is_datetime_arraylike([1, 2, 3])
658-
False
659-
>>> is_datetime_arraylike(pd.Index([1, 2, 3]))
660-
False
661-
>>> is_datetime_arraylike(pd.DatetimeIndex([1, 2, 3]))
662-
True
663-
"""
664-
if isinstance(arr, ABCDatetimeIndex):
665-
return True
666-
elif isinstance(arr, (np.ndarray, ABCSeries)):
667-
return (
668-
is_object_dtype(arr.dtype)
669-
and lib.infer_dtype(arr, skipna=False) == "datetime"
670-
)
671-
return getattr(arr, "inferred_type", None) == "datetime"
672-
673-
674602
def is_dtype_equal(source, target) -> bool:
675603
"""
676604
Check if two dtypes are equal.

pandas/core/generic.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,6 @@
7272
is_number,
7373
is_numeric_dtype,
7474
is_object_dtype,
75-
is_period_arraylike,
7675
is_re_compilable,
7776
is_scalar,
7877
is_timedelta64_dtype,
@@ -1342,7 +1341,7 @@ def __neg__(self):
13421341

13431342
def __pos__(self):
13441343
values = self._values
1345-
if is_bool_dtype(values) or is_period_arraylike(values):
1344+
if is_bool_dtype(values):
13461345
arr = values
13471346
elif (
13481347
is_numeric_dtype(values)

pandas/core/indexes/accessors.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
"""
22
datetimelike delegation
33
"""
4+
from typing import TYPE_CHECKING
5+
46
import numpy as np
57

68
from pandas.core.dtypes.common import (
79
is_categorical_dtype,
810
is_datetime64_dtype,
911
is_datetime64tz_dtype,
10-
is_datetime_arraylike,
1112
is_integer_dtype,
1213
is_list_like,
13-
is_period_arraylike,
14+
is_period_dtype,
1415
is_timedelta64_dtype,
1516
)
1617
from pandas.core.dtypes.generic import ABCSeries
@@ -21,9 +22,12 @@
2122
from pandas.core.indexes.datetimes import DatetimeIndex
2223
from pandas.core.indexes.timedeltas import TimedeltaIndex
2324

25+
if TYPE_CHECKING:
26+
from pandas import Series # noqa:F401
27+
2428

2529
class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin):
26-
def __init__(self, data, orig):
30+
def __init__(self, data: "Series", orig):
2731
if not isinstance(data, ABCSeries):
2832
raise TypeError(
2933
f"cannot convert an object of type {type(data)} to a datetimelike index"
@@ -45,12 +49,8 @@ def _get_values(self):
4549
elif is_timedelta64_dtype(data.dtype):
4650
return TimedeltaIndex(data, copy=False, name=self.name)
4751

48-
else:
49-
if is_period_arraylike(data):
50-
# TODO: use to_period_array
51-
return PeriodArray(data, copy=False)
52-
if is_datetime_arraylike(data):
53-
return DatetimeIndex(data, copy=False, name=self.name)
52+
elif is_period_dtype(data):
53+
return PeriodArray(data, copy=False)
5454

5555
raise TypeError(
5656
f"cannot convert an object of type {type(data)} to a datetimelike index"
@@ -137,7 +137,7 @@ class DatetimeProperties(Properties):
137137
Raises TypeError if the Series does not contain datetimelike values.
138138
"""
139139

140-
def to_pydatetime(self):
140+
def to_pydatetime(self) -> np.ndarray:
141141
"""
142142
Return the data as an array of native Python datetime objects.
143143
@@ -209,7 +209,7 @@ class TimedeltaProperties(Properties):
209209
Raises TypeError if the Series does not contain datetimelike values.
210210
"""
211211

212-
def to_pytimedelta(self):
212+
def to_pytimedelta(self) -> np.ndarray:
213213
"""
214214
Return an array of native `datetime.timedelta` objects.
215215
@@ -271,7 +271,7 @@ def components(self):
271271
2 0 0 0 2 0 0 0
272272
3 0 0 0 3 0 0 0
273273
4 0 0 0 4 0 0 0
274-
""" # noqa: E501
274+
"""
275275
return self._get_values().components.set_index(self._parent.index)
276276

277277
@property
@@ -303,7 +303,7 @@ class PeriodProperties(Properties):
303303
class CombinedDatetimelikeProperties(
304304
DatetimeProperties, TimedeltaProperties, PeriodProperties
305305
):
306-
def __new__(cls, data):
306+
def __new__(cls, data: "Series"):
307307
# CombinedDatetimelikeProperties isn't really instantiated. Instead
308308
# we need to choose which parent (datetime or timedelta) is
309309
# appropriate. Since we're checking the dtypes anyway, we'll just
@@ -330,9 +330,7 @@ def __new__(cls, data):
330330
return DatetimeProperties(data, orig)
331331
elif is_timedelta64_dtype(data.dtype):
332332
return TimedeltaProperties(data, orig)
333-
elif is_period_arraylike(data):
333+
elif is_period_dtype(data):
334334
return PeriodProperties(data, orig)
335-
elif is_datetime_arraylike(data):
336-
return DatetimeProperties(data, orig)
337335

338336
raise AttributeError("Can only use .dt accessor with datetimelike values")

pandas/core/indexes/category.py

-4
Original file line numberDiff line numberDiff line change
@@ -364,10 +364,6 @@ def __contains__(self, key: Any) -> bool:
364364
hash(key)
365365
return contains(self, key, container=self._engine)
366366

367-
def __array__(self, dtype=None) -> np.ndarray:
368-
""" the array interface, return my values """
369-
return np.array(self._data, dtype=dtype)
370-
371367
@Appender(Index.astype.__doc__)
372368
def astype(self, dtype, copy=True):
373369
if is_interval_dtype(dtype):

pandas/core/indexes/datetimes.py

-3
Original file line numberDiff line numberDiff line change
@@ -267,9 +267,6 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, dtype=None):
267267

268268
# --------------------------------------------------------------------
269269

270-
def __array__(self, dtype=None) -> np.ndarray:
271-
return np.asarray(self._data, dtype=dtype)
272-
273270
@cache_readonly
274271
def _is_dates_only(self) -> bool:
275272
"""

pandas/core/indexes/extension.py

+3
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,9 @@ def __iter__(self):
224224

225225
# ---------------------------------------------------------------------
226226

227+
def __array__(self, dtype=None) -> np.ndarray:
228+
return np.asarray(self._data, dtype=dtype)
229+
227230
@property
228231
def _ndarray_values(self) -> np.ndarray:
229232
return self._data._ndarray_values

pandas/core/indexes/period.py

-7
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
is_dtype_equal,
2020
is_float,
2121
is_integer,
22-
is_integer_dtype,
2322
is_object_dtype,
2423
is_scalar,
2524
pandas_dtype,
@@ -338,12 +337,6 @@ def _int64index(self) -> Int64Index:
338337
# ------------------------------------------------------------------------
339338
# Index Methods
340339

341-
def __array__(self, dtype=None) -> np.ndarray:
342-
if is_integer_dtype(dtype):
343-
return self.asi8
344-
else:
345-
return self.astype(object).values
346-
347340
def __array_wrap__(self, result, context=None):
348341
"""
349342
Gets called after a ufunc. Needs additional handling as

pandas/core/indexes/range.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def _data(self):
168168
return self._cached_data
169169

170170
@cache_readonly
171-
def _int64index(self):
171+
def _int64index(self) -> Int64Index:
172172
return Int64Index._simple_new(self._data, name=self.name)
173173

174174
def _get_data_as_items(self):

pandas/core/internals/blocks.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -3144,14 +3144,15 @@ def _safe_reshape(arr, new_shape):
31443144
return arr
31453145

31463146

3147-
def _putmask_smart(v, mask, n):
3147+
def _putmask_smart(v: np.ndarray, mask: np.ndarray, n) -> np.ndarray:
31483148
"""
31493149
Return a new ndarray, try to preserve dtype if possible.
31503150
31513151
Parameters
31523152
----------
3153-
v : `values`, updated in-place (array like)
3154-
mask : np.ndarray
3153+
v : np.ndarray
3154+
`values`, updated in-place.
3155+
mask : np.ndarray[bool]
31553156
Applies to both sides (array like).
31563157
n : `new values` either scalar or an array like aligned with `values`
31573158
@@ -3218,9 +3219,6 @@ def _putmask_preserve(nv, n):
32183219
# change the dtype if needed
32193220
dtype, _ = maybe_promote(n.dtype)
32203221

3221-
if is_extension_array_dtype(v.dtype) and is_object_dtype(dtype):
3222-
v = v._internal_get_values(dtype)
3223-
else:
3224-
v = v.astype(dtype)
3222+
v = v.astype(dtype)
32253223

32263224
return _putmask_preserve(v, n)

pandas/core/internals/managers.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,14 @@
2424
is_list_like,
2525
is_numeric_v_string_like,
2626
is_scalar,
27-
is_sparse,
2827
)
2928
from pandas.core.dtypes.concat import concat_compat
3029
from pandas.core.dtypes.dtypes import ExtensionDtype
3130
from pandas.core.dtypes.generic import ABCExtensionArray, ABCSeries
3231
from pandas.core.dtypes.missing import isna
3332

3433
import pandas.core.algorithms as algos
34+
from pandas.core.arrays.sparse import SparseDtype
3535
from pandas.core.base import PandasObject
3636
from pandas.core.indexers import maybe_convert_indices
3737
from pandas.core.indexes.api import Index, MultiIndex, ensure_index
@@ -843,8 +843,8 @@ def _interleave(self) -> np.ndarray:
843843

844844
# TODO: https://github.com/pandas-dev/pandas/issues/22791
845845
# Give EAs some input on what happens here. Sparse needs this.
846-
if is_sparse(dtype):
847-
dtype = dtype.subtype # type: ignore
846+
if isinstance(dtype, SparseDtype):
847+
dtype = dtype.subtype
848848
elif is_extension_array_dtype(dtype):
849849
dtype = "object"
850850

pandas/core/nanops.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -981,7 +981,7 @@ def nanskew(
981981
Examples
982982
--------
983983
>>> import pandas.core.nanops as nanops
984-
>>> s = pd.Series([1,np.nan, 1, 2])
984+
>>> s = pd.Series([1, np.nan, 1, 2])
985985
>>> nanops.nanskew(s)
986986
1.7320508075688787
987987
"""
@@ -1065,7 +1065,7 @@ def nankurt(
10651065
Examples
10661066
--------
10671067
>>> import pandas.core.nanops as nanops
1068-
>>> s = pd.Series([1,np.nan, 1, 3, 2])
1068+
>>> s = pd.Series([1, np.nan, 1, 3, 2])
10691069
>>> nanops.nankurt(s)
10701070
-1.2892561983471076
10711071
"""

0 commit comments

Comments
 (0)