Skip to content

BUG: Fix DataFrame constructor misclassification of array-like with 'name' attribute (#61443) #61451

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 3 commits into from
May 19, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
8 changes: 6 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@
BaseMaskedDtype,
ExtensionDtype,
)
from pandas.core.dtypes.generic import (
ABCIndex,
ABCSeries,
)
from pandas.core.dtypes.missing import (
isna,
notna,
Expand Down Expand Up @@ -795,12 +799,12 @@ def __init__(
dtype,
copy,
)
elif getattr(data, "name", None) is not None:
elif isinstance(data, (ABCSeries, ABCIndex)) and data.name is not None:
# i.e. Series/Index with non-None name
mgr = dict_to_mgr(
# error: Item "ndarray" of "Union[ndarray, Series, Index]" has no
# attribute "name"
{data.name: data}, # type: ignore[union-attr]
{data.name: data},
index,
columns,
dtype=dtype,
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/frame/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2780,6 +2780,18 @@ def test_construction_nan_value_timedelta64_dtype(self):
)
tm.assert_frame_equal(result, expected)

def test_dataframe_from_array_like_with_name_attribute(self):
class DummyArray(np.ndarray):
def __new__(cls, input_array):
obj = np.asarray(input_array).view(cls)
obj.name = "foo"
return obj

dummy = DummyArray(np.eye(3))
df = DataFrame(dummy)
expected = DataFrame(np.eye(3))
tm.assert_frame_equal(df, expected)


class TestDataFrameConstructorIndexInference:
def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):
Expand Down
Loading