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

fix(python): address DataFrame construction error with lists of numpy arrays #11905

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
4 changes: 4 additions & 0 deletions py-polars/polars/io/spreadsheet/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,10 @@ def _read_spreadsheet(
if hasattr(parser, "close"):
parser.close()

if not parsed_sheets:
param, value = ("id", sheet_id) if sheet_name is None else ("name", sheet_name)
raise ValueError(f"no matching sheets found when `sheet_{param}` is {value!r}")

if return_multi:
return parsed_sheets
return next(iter(parsed_sheets.values()))
Expand Down
6 changes: 5 additions & 1 deletion py-polars/polars/utils/_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -1024,7 +1024,11 @@ def _sequence_of_sequence_to_pydf(
local_schema_override = (
include_unknowns(schema_overrides, column_names) if schema_overrides else {}
)
if column_names and first_element and len(first_element) != len(column_names):
if (
column_names
and len(first_element) > 0
and len(first_element) != len(column_names)
):
raise ShapeError("the row data does not match the number of columns")

unpack_nested = False
Expand Down
30 changes: 30 additions & 0 deletions py-polars/tests/unit/io/test_spreadsheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,36 @@ def test_read_excel_basic_datatypes(
assert_frame_equal(df, df)


@pytest.mark.parametrize(
("read_spreadsheet", "source", "params"),
[
(pl.read_excel, "path_xlsx", {"engine": "xlsx2csv"}),
(pl.read_excel, "path_xlsx", {"engine": "openpyxl"}),
(pl.read_excel, "path_xlsb", {"engine": "pyxlsb"}),
(pl.read_ods, "path_ods", {}),
],
)
def test_read_invalid_worksheet(
read_spreadsheet: Callable[..., dict[str, pl.DataFrame]],
source: str,
params: dict[str, str],
request: pytest.FixtureRequest,
) -> None:
spreadsheet_path = request.getfixturevalue(source)
for param, sheet_id, sheet_name in (
("id", 999, None),
("name", None, "not_a_sheet_name"),
):
value = sheet_id if param == "id" else sheet_name
with pytest.raises(
ValueError,
match=f"no matching sheets found when `sheet_{param}` is {value!r}",
):
read_spreadsheet(
spreadsheet_path, sheet_id=sheet_id, sheet_name=sheet_name, **params
)


@pytest.mark.parametrize("engine", ["xlsx2csv", "openpyxl"])
def test_write_excel_bytes(engine: Literal["xlsx2csv", "openpyxl", "pyxlsb"]) -> None:
df = pl.DataFrame({"A": [1, 2, 3, 4, 5]})
Expand Down
4 changes: 4 additions & 0 deletions py-polars/tests/unit/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,10 @@ def test_init_ndarray(monkeypatch: Any) -> None:
assert df.shape == (2, 1)
assert df.rows() == [([0, 1, 2, 3, 4],), ([5, 6, 7, 8, 9],)]

test_rows = [(1, 2), (3, 4)]
df = pl.DataFrame([np.array(test_rows[0]), np.array(test_rows[1])], orient="row")
assert_frame_equal(df, pl.DataFrame(test_rows, orient="row"))

# numpy arrays containing NaN
df0 = pl.DataFrame(
data={"x": [1.0, 2.5, float("nan")], "y": [4.0, float("nan"), 6.5]},
Expand Down
2 changes: 1 addition & 1 deletion py-polars/tests/unit/test_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def test_string_numeric_comp_err() -> None:
def test_panic_error() -> None:
with pytest.raises(
pl.PolarsPanicError,
match="""dimensions cannot be empty""",
match="dimensions cannot be empty",
):
pl.Series("a", [1, 2, 3]).reshape(())

Expand Down