pandas-dev/pandas · #72231
BUG: clear error for a scalar row after a list-like row (GH#29213)
pandas/core/internals/construction.py30 + / 1 −
@@ -854,6 +854,8 @@ def to_arrays( has_str_rows = not is_scalar(data[0]) and _warn_if_str_rows( set(map(type, data)) )+ if is_list_like(data[0]):+ _validate_scalar_rows(data) # last ditch effort # GH#23985, GH#49593: if all rows are arrays with a uniform@@ -905,7 +907,11 @@ def _list_to_arrays( else: if _warn_if_str_rows(row_types): check_ragged = False- lengths = {1 if is_scalar(row) and isna(row) else len(row) for row in data}+ null_rows = _validate_scalar_rows(data)+ lengths = {+ 1 if is_null else len(row)+ for row, is_null in zip(data, null_rows, strict=True)+ } if check_ragged and len(lengths) > 1: warnings.warn( "Constructing a DataFrame from a list of sequences with mismatched "@@ -924,6 +930,29 @@ def _list_to_arrays( return content +def _validate_scalar_rows(data: list[Any]) -> list[bool]:+ # GH#29213 a non-iterable row would otherwise fail later with an opaque error;+ # a null row after a tuple row is padded by lib.to_object_array_tuples.+ # Returns whether each row is such a null row.+ allow_null = isinstance(data[0], tuple)+ null_rows = []+ for i, row in enumerate(data):+ is_null = allow_null and is_scalar(row) and isna(row)+ null_rows.append(is_null)+ if is_null:+ continue+ try:+ iter(row)+ except TypeError as err:+ raise TypeError(+ "When the first row is list-like, every row must be list-like, "+ f"but the row at position {i} has type {type(row).__name__}. To "+ "store list-likes as values of a single column, construct a "+ "Series and call to_frame() instead."+ ) from err+ return null_rows++ def _warn_if_str_rows(row_types: set[type]) -> bool: # GH#50461 called when the first row is list-like. Returns whether a str or # bytes row was found, in which case the caller skips the mismatched-lengthspandas/tests/frame/constructors/test_from_dict.py6 + / 0 −
@@ -252,6 +252,12 @@ def test_from_dict_orient_index_list_then_str_deprecated(self, value, row): expected = pd.DataFrame([["A1", "A2"], row], index=["a", "b"]) tm.assert_frame_equal(result, expected) + def test_from_dict_orient_index_list_then_scalar_raises(self):+ # GH#29213+ msg = "When the first row is list-like, every row must be list-like"+ with pytest.raises(TypeError, match=msg):+ pd.DataFrame.from_dict({"a": [1, 2, 3], "b": 1.5}, orient="index")+ def test_from_dict_orient_invalid(self): msg = ( "Expected 'index', 'columns' or 'tight' for orient parameter. "pandas/tests/frame/constructors/test_from_records.py5 + / 0 −
@@ -220,6 +220,11 @@ def __iter__(self) -> Iterator: expected = pd.DataFrame.from_records(tups) tm.assert_frame_equal(result, expected) + def test_from_records_non_iterable_first_record(self):+ # GH#29213 a non-list-like first record keeps the original error+ with pytest.raises(TypeError, match="'object' object is not iterable"):+ pd.DataFrame.from_records([object(), object()])+ def test_from_records_len0_with_columns(self): # GH#2633 result = pd.DataFrame.from_records([], index="foo", columns=["foo", "bar"])pandas/tests/frame/test_constructors.py37 + / 0 −
@@ -7,6 +7,7 @@ namedtuple, ) from collections.abc import Iterator+import ctypes from dataclasses import ( dataclass, make_dataclass,@@ -2644,6 +2645,42 @@ def test_construct_listlike_then_str_row_deprecated(self, first_row, str_row): with tm.assert_produces_warning(Pandas4Warning, match=msg): pd.DataFrame([first_row, str_row]) + @pytest.mark.parametrize("first_row", [[1, 2], np.array([1, 2]), {1, 2}], ids=type)+ @pytest.mark.parametrize(+ "row",+ [3, np.int64(3), np.array(3), np.nan, None, pd.Timestamp("2020-01-01")],+ )+ def test_construct_listlike_then_scalar_row_raises(self, first_row, row):+ # GH#29213+ msg = "the row at position 2 has type"+ with pytest.raises(TypeError, match=msg):+ pd.DataFrame([first_row, first_row, row])++ @pytest.mark.parametrize(+ "row", [3, np.int64(3), np.array(3), pd.Timestamp("2020-01-01")]+ )+ def test_construct_tuple_then_scalar_row_raises(self, row):+ # GH#29213 null rows are padded, see test_construct_tuple_then_null_row_padded+ msg = "the row at position 2 has type"+ with pytest.raises(TypeError, match=msg):+ pd.DataFrame([(1, 2), (1, 2), row])++ @pytest.mark.parametrize("row", [np.nan, None])+ def test_construct_tuple_then_null_row_padded(self, row):+ # GH#29213 a null row after a tuple row is still padded with NaN+ msg = "mismatched lengths is deprecated"+ with tm.assert_produces_warning(Pandas4Warning, match=msg):+ result = pd.DataFrame([(1, 2), (1, 2), row])+ expected = pd.DataFrame([[1.0, 2.0], [1.0, 2.0], [np.nan, np.nan]])+ tm.assert_frame_equal(result, expected)++ def test_construct_listlike_then_iterable_row(self):+ # GH#29213 a row that is iterable but not list-like is still accepted+ row = (ctypes.c_int * 2)(5, 6)+ result = pd.DataFrame([np.array([1, 2]), row])+ expected = pd.DataFrame([[1, 2], [5, 6]])+ tm.assert_frame_equal(result, expected)+ def test_constructor_categorical_series(self): items = [1, 2, 3, 1] exp = pd.Series(items).astype("category")