Skip to content

REF: ensure to_arrays returns matched-length arrays/columns #43099

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
2 changes: 2 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2323,6 +2323,8 @@ def _from_arrays(

manager = get_option("mode.data_manager")
columns = ensure_index(columns)
if len(columns) != len(arrays):
raise ValueError("len(columns) must match len(arrays)")
mgr = arrays_to_mgr(
arrays,
columns,
Expand Down
17 changes: 17 additions & 0 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ def dict_to_mgr(
arrays.loc[missing] = [val] * missing.sum()

arrays = list(arrays)
data_names = ensure_index(columns)

else:
keys = list(data.keys())
Expand Down Expand Up @@ -738,6 +739,17 @@ def to_arrays(
) -> tuple[list[ArrayLike], Index]:
"""
Return list of arrays, columns.

Returns
-------
list[ArrayLike]
These will become columns in a DataFrame.
Index
This will become frame.columns.

Notes
-----
Ensures that len(result_arrays) == len(result_index).
"""
if isinstance(data, ABCDataFrame):
# see test_from_records_with_index_data, test_from_records_bad_index_column
Expand Down Expand Up @@ -783,6 +795,11 @@ def to_arrays(
)
if columns is None:
columns = ibase.default_index(len(data))
elif len(columns) > len(data):
raise ValueError("len(columns) > len(data)")
elif len(columns) < len(data):
# doing this here is akin to a pre-emptive reindex
data = data[: len(columns)]
return data, columns

elif isinstance(data, np.ndarray) and data.dtype.names is not None:
Expand Down