Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH/BUG: implement __iter__ for IntegerArray so conversions (to_dict, tolist, etc.) return python native types #37377

Closed
wants to merge 27 commits into from
Closed
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
07782bc
TST: add tests from OP
arw2019 Oct 24, 2020
1b164c3
ENH: implement __iter__ from IntegerArray
arw2019 Oct 24, 2020
142c81f
feedback: move __iter__ method to base class
arw2019 Oct 24, 2020
3357901
TST: parametrize Int tests on dtype
arw2019 Oct 24, 2020
e38934e
TST: add floating tests
arw2019 Oct 24, 2020
fa2166d
Merge remote-tracking branch 'upstream/master' into GH29738
arw2019 Oct 24, 2020
c32aafa
TST: add boolean tests
arw2019 Oct 24, 2020
2eb7219
TST: #346654
arw2019 Oct 24, 2020
db4154d
feedback: gather tests in separate file + use fixtures
arw2019 Oct 30, 2020
30d2f09
TST: remove tests from original locations
arw2019 Oct 30, 2020
26314f7
Merge remote-tracking branch 'upstream/master' into GH29738
arw2019 Oct 30, 2020
8d81ec9
Merge remote-tracking branch 'upstream/master' into GH29738
arw2019 Nov 1, 2020
d7fced7
TST: rewrite expected construction using pd.array
arw2019 Nov 1, 2020
7bdc0ac
TST: add comment
arw2019 Nov 1, 2020
9bf6b25
TST: skip float-string conversion, reason:M f-p precision
arw2019 Nov 1, 2020
ec837c0
TST/BUG: correct test rewrite
arw2019 Nov 1, 2020
c7db14a
TST: skip string conversion test due to fp-precision issues
arw2019 Nov 1, 2020
e70a7df
TST: DRY the code using data fixture
arw2019 Nov 1, 2020
ff1ede7
CLN: remove unused code
arw2019 Nov 1, 2020
1df019c
TST/BUG: implement jorisvandenbossche suggestion to fix astype(str) t…
arw2019 Nov 3, 2020
2a5df3e
TST: skip boolean combine_add test
arw2019 Nov 3, 2020
79582d4
Merge remote-tracking branch 'upstream/master' into GH29738
arw2019 Nov 5, 2020
1206096
Merge branch 'master' of https://github.com/pandas-dev/pandas into GH…
arw2019 Nov 30, 2020
bcf0896
skip str astype tests for Float32Dtype
arw2019 Nov 30, 2020
cde954b
Merge branch 'master' of https://github.com/pandas-dev/pandas into GH…
arw2019 Dec 31, 2020
d9f4809
Merge branch 'master' of https://github.com/pandas-dev/pandas into GH…
arw2019 Jan 31, 2021
225a260
docstring fix
arw2019 Jan 31, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas/core/arrays/masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def __iter__(self):
if self._mask[i]:
yield self.dtype.na_value
else:
yield self._data[i]
yield self._data[i].item()

def __len__(self) -> int:
return len(self._data)
Expand Down
1 change: 1 addition & 0 deletions pandas/tests/extension/base/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,5 @@ class TestMyDtype(BaseDtypeTests):
BaseNumericReduceTests,
)
from .reshaping import BaseReshapingTests # noqa
from .return_types import BaseReturnTypeTests # noqa
from .setitem import BaseSetitemTests # noqa
4 changes: 2 additions & 2 deletions pandas/tests/extension/base/casting.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ def test_tolist(self, data):

def test_astype_str(self, data):
result = pd.Series(data[:5]).astype(str)
expected = pd.Series([str(x) for x in data[:5]], dtype=str)
expected = pd.Series(data[:5], dtype=str)
self.assert_series_equal(result, expected)

def test_astype_string(self, data):
# GH-33465
result = pd.Series(data[:5]).astype("string")
expected = pd.Series([str(x) for x in data[:5]], dtype="string")
expected = pd.Series(data[:5], dtype="string")
self.assert_series_equal(result, expected)

def test_to_numpy(self, data):
Expand Down
16 changes: 9 additions & 7 deletions pandas/tests/extension/base/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,15 @@ def test_combine_add(self, data_repeated):
s1 = pd.Series(orig_data1)
s2 = pd.Series(orig_data2)
result = s1.combine(s2, lambda x1, x2: x1 + x2)
with np.errstate(over="ignore"):
expected = pd.Series(
orig_data1._from_sequence(
[a + b for (a, b) in zip(list(orig_data1), list(orig_data2))]
)
)
self.assert_series_equal(result, expected)

expected = pd.Series(
pd.array([a + b for (a, b) in zip(list(orig_data1), list(orig_data2))]),
dtype=orig_data1.dtype,
)

# TODO: expected currently has an incorrect dtype
# fix construction and set check_type=True in assertion
self.assert_series_equal(result, expected, check_dtype=False)

val = s1.iloc[0]
result = s1.combine(val, lambda x1, x2: x1 + x2)
Expand Down
60 changes: 60 additions & 0 deletions pandas/tests/extension/base/return_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import pytest
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My previous comment was actually about moving them to a file in tests/arrays/masked/ (so to share the test with the different nullable dtypes).

Now, I am also fine to move it to the base extension tests as you did here, but then we should add this to all EAs. If it's only activated for nullable floating/integer/boolean as is done now, then it should move to tests/arrays/masked/, as it's not a general test for all EAs.

Making it truly generic is probably a bit annoying (you need to know the exact expected type for the scalars), but so maybe the subclasses can override get_native_dtype where needed? Or maybe it can be an attribute on the test class (if it's always a single type for each dtype, then that's simpler)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My previous comment was actually about moving them to a file in tests/arrays/masked/ (so to share the test with the different nullable dtypes).

Now, I am also fine to move it to the base extension tests as you did here, but then we should add this to all EAs. If it's only activated for nullable floating/integer/boolean as is done now, then it should move to tests/arrays/masked/, as it's not a general test for all EAs.

I did misunderstand but this makes sense

Making it truly generic is probably a bit annoying (you need to know the exact expected type for the scalars), but so maybe the subclasses can override get_native_dtype where needed? Or maybe it can be an attribute on the test class (if it's always a single type for each dtype, then that's simpler)

This sounds like the way to go. I like not having to keep a registry of the mapping between scalars and native types in a single place


from pandas.core.dtypes.common import is_bool_dtype, is_float_dtype, is_integer_dtype

import pandas as pd
from pandas import isna

from .base import BaseExtensionTests


@pytest.fixture(
params=[
lambda df: df.to_dict()["A"].values(),
lambda df: [record["A"] for record in df.to_dict(orient="records")],
]
)
def frame_conversion(request):
return request.param


class BaseReturnTypeTests(BaseExtensionTests):
def get_native_dtype(self, dtype):
if is_integer_dtype(dtype):
return int
elif is_float_dtype(dtype):
return float
elif is_bool_dtype(dtype):
return bool
else:
raise ValueError("invalid dtype provided")

@pytest.mark.parametrize(
"func",
[
lambda s: s.tolist(),
lambda s: s.to_dict().values(),
lambda s: [v for _, v in s.iteritems()],
lambda s: list(iter(s)),
],
)
def test_series(self, all_data, func):
# GH 29738
s = pd.Series(all_data)
native_dtype = self.get_native_dtype(all_data.dtype)

assert all(isinstance(val, native_dtype) or isna(val) for val in func(s))

@pytest.mark.parametrize(
"func",
[
lambda df: df.to_dict()["A"].values(),
lambda df: [record["A"] for record in df.to_dict(orient="records")],
],
)
def test_frame(self, all_data, func):
# GH 29738
s = pd.DataFrame({"A": all_data})
native_dtype = self.get_native_dtype(all_data.dtype)

assert all(isinstance(val, native_dtype) or isna(val) for val in func(s))
4 changes: 4 additions & 0 deletions pandas/tests/extension/test_boolean.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ class TestMissing(base.BaseMissingTests):
pass


class TestReturnTypes(base.BaseReturnTypeTests):
pass


class TestArithmeticOps(base.BaseArithmeticOpsTests):
implements = {"__sub__", "__rsub__"}

Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/extension/test_floating.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ class TestMissing(base.BaseMissingTests):
pass


class TestReturnTypes(base.BaseReturnTypeTests):
pass


class TestMethods(base.BaseMethodsTests):
@pytest.mark.skip(reason="uses nullable integer")
def test_value_counts(self, all_data, dropna):
Expand Down
4 changes: 4 additions & 0 deletions pandas/tests/extension/test_integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,10 @@ class TestMissing(base.BaseMissingTests):
pass


class TestReturnTypes(base.BaseReturnTypeTests):
pass


class TestMethods(base.BaseMethodsTests):
@pytest.mark.skip(reason="uses nullable integer")
def test_value_counts(self, all_data, dropna):
Expand Down