Skip to content

BUG: Fixed DataFrame.__repr__ Type Error when column dtype is np.record (GH 48526) #48637

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

Merged
merged 17 commits into from
Apr 21, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,7 @@ Conversion
- Bug in :meth:`Series.to_numpy` converting to NumPy array before applying ``na_value`` (:issue:`48951`)
- Bug in :meth:`DataFrame.astype` not copying data when converting to pyarrow dtype (:issue:`50984`)
- Bug in :func:`to_datetime` was not respecting ``exact`` argument when ``format`` was an ISO8601 format (:issue:`12649`)
- Bug in :meth:`DataFrame.__repr__` incorrectly raising a ``TypeError`` when the dtype of a column is ``np.record`` (:issue:`48526`)
Copy link
Member

Choose a reason for hiding this comment

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

Can you move this to 2.1

Copy link
Contributor Author

@RaphSku RaphSku Apr 20, 2023

Choose a reason for hiding this comment

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

Of course, done

- Bug in :meth:`TimedeltaArray.astype` raising ``TypeError`` when converting to a pyarrow duration type (:issue:`49795`)
- Bug in :meth:`DataFrame.eval` and :meth:`DataFrame.query` raising for extension array dtypes (:issue:`29618`, :issue:`50261`, :issue:`31913`)

Expand Down
33 changes: 33 additions & 0 deletions pandas/core/dtypes/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,9 @@ def _isna_array(values: ArrayLike, inf_as_na: bool = False):
# "Union[ndarray[Any, Any], ExtensionArraySupportsAnyAll]", variable has
# type "ndarray[Any, dtype[bool_]]")
result = values.isna() # type: ignore[assignment]
elif isinstance(values, np.recarray):
# GH 48526
result = _isna_recarray_dtype(values, inf_as_na=inf_as_na)
elif is_string_or_object_np_dtype(values.dtype):
result = _isna_string_dtype(values, inf_as_na=inf_as_na)
elif needs_i8_conversion(dtype):
Expand Down Expand Up @@ -321,6 +324,36 @@ def _isna_string_dtype(values: np.ndarray, inf_as_na: bool) -> npt.NDArray[np.bo
return result


def _isna_recarray_dtype(values: np.recarray, inf_as_na: bool) -> npt.NDArray[np.bool_]:
result = np.zeros(values.shape, dtype=bool)
for i, record in enumerate(values):
does_record_contain_nan = np.zeros(len(record), dtype=bool)
if inf_as_na:
Copy link
Member

Choose a reason for hiding this comment

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

Instead of if inf_as_na everywhere could you create a checker function initially like

if inf_as_na:
    is_missing = lambda x: np.isnan(x) or np.isinf(x)
else:
    is_missing = lambda x: np.isnan(x)

And use that in the loop?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@mroeschke I rewrote the function to increase readbility. What do you think about the change?

does_record_contain_inf = np.zeros(len(record), dtype=bool)
for j, element in enumerate(record):
Copy link
Member

Choose a reason for hiding this comment

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

Can you just call isnan and/or isinf on record?

Copy link
Contributor Author

@RaphSku RaphSku Apr 20, 2023

Choose a reason for hiding this comment

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

@mroeschke I used isnan_all for the record and I rewrote a little bit the isinf part but I cannot use isinfdirectly on the record since it will throw a TypeError when the record value is a string. But I hope the way I rewrote the method still improved on the previous version.

if element != element:
does_record_contain_nan[j] = True
else:
does_record_contain_nan[j] = False
if inf_as_na:
try:
if np.isinf(element):
does_record_contain_inf[j] = True
else:
does_record_contain_inf[j] = False
except TypeError:
does_record_contain_inf[j] = False

if inf_as_na:
result[i] = np.any(
np.logical_or(does_record_contain_nan, does_record_contain_inf)
)
else:
result[i] = np.any(does_record_contain_nan)

return result


@overload
def notna(obj: Scalar) -> bool:
...
Expand Down
37 changes: 37 additions & 0 deletions pandas/tests/frame/test_repr_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,43 @@ def test_datetime64tz_slice_non_truncate(self):
result = repr(df)
assert result == expected

def test_to_records_no_typeerror_in_repr(self):
# GH 48526
df = DataFrame([["a", "b"], ["c", "d"], ["e", "f"]], columns=["left", "right"])
df["record"] = df[["left", "right"]].to_records()
expected = """ left right record
0 a b [0, a, b]
1 c d [1, c, d]
2 e f [2, e, f]"""
result = repr(df)
assert result == expected

def test_to_records_with_na_record_value(self):
Copy link
Member

Choose a reason for hiding this comment

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

Would be good to have tests for inf as well here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@mroeschke I added 2 tests for inf, is the expected result what you would also expect?

# GH 48526
df = DataFrame(
[["a", np.nan], ["c", "d"], ["e", "f"]], columns=["left", "right"]
)
df["record"] = df[["left", "right"]].to_records()
expected = """ left right record
0 a NaN [0, a, nan]
1 c d [1, c, d]
2 e f [2, e, f]"""
result = repr(df)
assert result == expected

def test_to_records_with_na_record(self):
# GH 48526
df = DataFrame(
[["a", "b"], [np.nan, np.nan], ["e", "f"]], columns=[np.nan, "right"]
)
df["record"] = df[[np.nan, "right"]].to_records()
expected = """ NaN right record
0 a b [0, a, b]
1 NaN NaN [1, nan, nan]
2 e f [2, e, f]"""
result = repr(df)
assert result == expected

def test_masked_ea_with_formatter(self):
# GH#39336
df = DataFrame(
Expand Down