Skip to content

ENH: DtypeWarning message enhancement #58250

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
Show file tree
Hide file tree
Changes from all 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/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Other enhancements
- Support reading value labels from Stata 108-format (Stata 6) and earlier files (:issue:`58154`)
- Users can globally disable any ``PerformanceWarning`` by setting the option ``mode.performance_warnings`` to ``False`` (:issue:`56920`)
- :meth:`Styler.format_index_names` can now be used to format the index and column names (:issue:`48936` and :issue:`47489`)
- :class:`.errors.DtypeWarning` improved to include column names when mixed data types are detected (:issue:`58174`)
- :meth:`DataFrame.cummin`, :meth:`DataFrame.cummax`, :meth:`DataFrame.cumprod` and :meth:`DataFrame.cumsum` methods now have a ``numeric_only`` parameter (:issue:`53072`)
- :meth:`DataFrame.fillna` and :meth:`Series.fillna` can now accept ``value=None``; for non-object dtype the corresponding NA value will be used (:issue:`57723`)

Expand Down
2 changes: 1 addition & 1 deletion pandas/errors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ class DtypeWarning(Warning):
... ) # doctest: +SKIP
>>> df.to_csv("test.csv", index=False) # doctest: +SKIP
>>> df2 = pd.read_csv("test.csv") # doctest: +SKIP
... # DtypeWarning: Columns (0) have mixed types
... # DtypeWarning: Columns (0: a) have mixed types

Important to notice that ``df2`` will contain both `str` and `int` for the
same input, '1'.
Expand Down
12 changes: 8 additions & 4 deletions pandas/io/parsers/c_parser_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def read(
if self.low_memory:
chunks = self._reader.read_low_memory(nrows)
# destructive to chunks
data = _concatenate_chunks(chunks)
data = _concatenate_chunks(chunks, self.names) # type: ignore[has-type]

else:
data = self._reader.read(nrows)
Expand Down Expand Up @@ -358,7 +358,9 @@ def _maybe_parse_dates(self, values, index: int, try_parse_dates: bool = True):
return values


def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict:
def _concatenate_chunks(
chunks: list[dict[int, ArrayLike]], column_names: list[str]
) -> dict:
"""
Concatenate chunks of data read with low_memory=True.

Expand All @@ -381,10 +383,12 @@ def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict:
else:
result[name] = concat_compat(arrs)
if len(non_cat_dtypes) > 1 and result[name].dtype == np.dtype(object):
warning_columns.append(str(name))
warning_columns.append(column_names[name])

if warning_columns:
warning_names = ",".join(warning_columns)
warning_names = ", ".join(
[f"{index}: {name}" for index, name in enumerate(warning_columns)]
)
warning_message = " ".join(
[
f"Columns ({warning_names}) have mixed types. "
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/parser/common/test_chunksize.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def test_warn_if_chunks_have_mismatched_type(all_parsers):
else:
df = parser.read_csv_check_warnings(
warning_type,
r"Columns \(0\) have mixed types. "
r"Columns \(0: a\) have mixed types. "
"Specify dtype option on import or set low_memory=False.",
buf,
)
Expand Down
8 changes: 5 additions & 3 deletions pandas/tests/io/parser/test_concatenate_chunks.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def test_concatenate_chunks_pyarrow():
{0: ArrowExtensionArray(pa.array([1.5, 2.5]))},
{0: ArrowExtensionArray(pa.array([1, 2]))},
]
result = _concatenate_chunks(chunks)
result = _concatenate_chunks(chunks, ["column_0", "column_1"])
expected = ArrowExtensionArray(pa.array([1.5, 2.5, 1.0, 2.0]))
tm.assert_extension_array_equal(result[0], expected)

Expand All @@ -28,8 +28,10 @@ def test_concatenate_chunks_pyarrow_strings():
{0: ArrowExtensionArray(pa.array([1.5, 2.5]))},
{0: ArrowExtensionArray(pa.array(["a", "b"]))},
]
with tm.assert_produces_warning(DtypeWarning, match="have mixed types"):
result = _concatenate_chunks(chunks)
with tm.assert_produces_warning(
DtypeWarning, match="Columns \\(0: column_0\\) have mixed types"
):
result = _concatenate_chunks(chunks, ["column_0", "column_1"])
expected = np.concatenate(
[np.array([1.5, 2.5], dtype=object), np.array(["a", "b"])]
)
Expand Down