Skip to content

Commit 26576a8

Browse files
authored
TYP: core.internals (#37058)
1 parent 01432fb commit 26576a8

File tree

8 files changed

+49
-28
lines changed

8 files changed

+49
-28
lines changed

pandas/core/arrays/base.py

+13
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,19 @@ def _formatter(self, boxed: bool = False) -> Callable[[Any], Optional[str]]:
10811081
# Reshaping
10821082
# ------------------------------------------------------------------------
10831083

1084+
def transpose(self, *axes) -> "ExtensionArray":
1085+
"""
1086+
Return a transposed view on this array.
1087+
1088+
Because ExtensionArrays are always 1D, this is a no-op. It is included
1089+
for compatibility with np.ndarray.
1090+
"""
1091+
return self[:]
1092+
1093+
@property
1094+
def T(self) -> "ExtensionArray":
1095+
return self.transpose()
1096+
10841097
def ravel(self, order="C") -> "ExtensionArray":
10851098
"""
10861099
Return a flattened view on this array.

pandas/core/arrays/sparse/array.py

-13
Original file line numberDiff line numberDiff line change
@@ -1310,19 +1310,6 @@ def mean(self, axis=0, *args, **kwargs):
13101310
nsparse = self.sp_index.ngaps
13111311
return (sp_sum + self.fill_value * nsparse) / (ct + nsparse)
13121312

1313-
def transpose(self, *axes) -> "SparseArray":
1314-
"""
1315-
Returns the SparseArray.
1316-
"""
1317-
return self
1318-
1319-
@property
1320-
def T(self) -> "SparseArray":
1321-
"""
1322-
Returns the SparseArray.
1323-
"""
1324-
return self
1325-
13261313
# ------------------------------------------------------------------------
13271314
# Ufuncs
13281315
# ------------------------------------------------------------------------

pandas/core/internals/blocks.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from datetime import datetime, timedelta
22
import inspect
33
import re
4-
from typing import TYPE_CHECKING, Any, List, Optional
4+
from typing import TYPE_CHECKING, Any, List, Optional, Type, Union, cast
55
import warnings
66

77
import numpy as np
@@ -93,6 +93,8 @@ class Block(PandasObject):
9393
Index-ignorant; let the container take care of that
9494
"""
9595

96+
values: Union[np.ndarray, ExtensionArray]
97+
9698
__slots__ = ["_mgr_locs", "values", "ndim"]
9799
is_numeric = False
98100
is_float = False
@@ -194,7 +196,9 @@ def _consolidate_key(self):
194196
@property
195197
def is_view(self) -> bool:
196198
""" return a boolean if I am possibly a view """
197-
return self.values.base is not None
199+
values = self.values
200+
values = cast(np.ndarray, values)
201+
return values.base is not None
198202

199203
@property
200204
def is_categorical(self) -> bool:
@@ -1465,6 +1469,7 @@ def where_func(cond, values, other):
14651469
result_blocks: List["Block"] = []
14661470
for m in [mask, ~mask]:
14671471
if m.any():
1472+
result = cast(np.ndarray, result) # EABlock overrides where
14681473
taken = result.take(m.nonzero()[0], axis=axis)
14691474
r = maybe_downcast_numeric(taken, self.dtype)
14701475
nb = self.make_block(r.T, placement=self.mgr_locs[m])
@@ -1619,6 +1624,8 @@ class ExtensionBlock(Block):
16191624
_validate_ndim = False
16201625
is_extension = True
16211626

1627+
values: ExtensionArray
1628+
16221629
def __init__(self, values, placement, ndim=None):
16231630
"""
16241631
Initialize a non-consolidatable block.
@@ -2197,9 +2204,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
21972204
if copy:
21982205
# this should be the only copy
21992206
values = values.copy()
2200-
if getattr(values, "tz", None) is None:
2201-
values = DatetimeArray(values).tz_localize("UTC")
2202-
values = values.tz_convert(dtype.tz)
2207+
values = DatetimeArray._simple_new(values.view("i8"), dtype=dtype)
22032208
return self.make_block(values)
22042209

22052210
# delegate
@@ -2243,6 +2248,8 @@ def set(self, locs, values):
22432248
class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
22442249
""" implement a datetime64 block with a tz attribute """
22452250

2251+
values: DatetimeArray
2252+
22462253
__slots__ = ()
22472254
is_datetimetz = True
22482255
is_extension = True
@@ -2670,6 +2677,8 @@ def get_block_type(values, dtype=None):
26702677
dtype = dtype or values.dtype
26712678
vtype = dtype.type
26722679

2680+
cls: Type[Block]
2681+
26732682
if is_sparse(dtype):
26742683
# Need this first(ish) so that Sparse[datetime] is sparse
26752684
cls = ExtensionBlock

pandas/core/internals/construction.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import numpy.ma as ma
1010

1111
from pandas._libs import lib
12-
from pandas._typing import Axis, DtypeObj, Scalar
12+
from pandas._typing import Axis, DtypeObj, Label, Scalar
1313

1414
from pandas.core.dtypes.cast import (
1515
construct_1d_arraylike_from_scalar,
@@ -436,7 +436,7 @@ def get_names_from_index(data):
436436
if not has_some_name:
437437
return ibase.default_index(len(data))
438438

439-
index = list(range(len(data)))
439+
index: List[Label] = list(range(len(data)))
440440
count = 0
441441
for i, s in enumerate(data):
442442
n = getattr(s, "name", None)

pandas/tests/extension/base/reshaping.py

+14
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,20 @@ def test_ravel(self, data):
333333
assert data[0] == data[1]
334334

335335
def test_transpose(self, data):
336+
result = data.transpose()
337+
assert type(result) == type(data)
338+
339+
# check we get a new object
340+
assert result is not data
341+
342+
# If we ever _did_ support 2D, shape should be reversed
343+
assert result.shape == data.shape[::-1]
344+
345+
# Check that we have a view, not a copy
346+
result[0] = result[1]
347+
assert data[0] == data[1]
348+
349+
def test_transpose_frame(self, data):
336350
df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"])
337351
result = df.T
338352
expected = pd.DataFrame(

pandas/tests/extension/test_numpy.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,8 @@ def test_merge_on_extension_array_duplicates(self, data):
377377
super().test_merge_on_extension_array_duplicates(data)
378378

379379
@skip_nested
380-
def test_transpose(self, data):
381-
super().test_transpose(data)
380+
def test_transpose_frame(self, data):
381+
super().test_transpose_frame(data)
382382

383383

384384
class TestSetitem(BaseNumPyTests, base.BaseSetitemTests):

pandas/tests/extension/test_sparse.py

+4
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,10 @@ def test_merge(self, data, na_value):
155155
self._check_unsupported(data)
156156
super().test_merge(data, na_value)
157157

158+
@pytest.mark.xfail(reason="SparseArray does not support setitem")
159+
def test_transpose(self, data):
160+
super().test_transpose(data)
161+
158162

159163
class TestGetitem(BaseSparseTests, base.BaseGetitemTests):
160164
def test_get(self, data):

setup.cfg

-6
Original file line numberDiff line numberDiff line change
@@ -187,12 +187,6 @@ check_untyped_defs=False
187187
[mypy-pandas.core.indexes.multi]
188188
check_untyped_defs=False
189189

190-
[mypy-pandas.core.internals.blocks]
191-
check_untyped_defs=False
192-
193-
[mypy-pandas.core.internals.construction]
194-
check_untyped_defs=False
195-
196190
[mypy-pandas.core.resample]
197191
check_untyped_defs=False
198192

0 commit comments

Comments
 (0)