Skip to content

Commit 09d4a63

Browse files
committed
BUG: Fix DataFrame constructor misclassification of array-like with 'name' attribute
Previously, any object with a .name attribute (like some vtkArray-like objects) was assumed to be a Series or Index, causing the constructor to misinterpret the input. This fix ensures we only apply the named-Index/Series logic when the input is actually an instance of ABCSeries or ABCIndex *and* has a non-None name. Closes #61443.
1 parent 5aa78c0 commit 09d4a63

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

pandas/core/frame.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@
116116
isna,
117117
notna,
118118
)
119+
from pandas.core.dtypes.generic import (
120+
ABCSeries,
121+
ABCIndex
122+
)
119123

120124
from pandas.core import (
121125
algorithms,
@@ -795,7 +799,7 @@ def __init__(
795799
dtype,
796800
copy,
797801
)
798-
elif getattr(data, "name", None) is not None:
802+
elif isinstance(data, (ABCSeries, ABCIndex)) and data.name is not None:
799803
# i.e. Series/Index with non-None name
800804
mgr = dict_to_mgr(
801805
# error: Item "ndarray" of "Union[ndarray, Series, Index]" has no

pandas/tests/frame/test_constructors.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2780,6 +2780,17 @@ def test_construction_nan_value_timedelta64_dtype(self):
27802780
)
27812781
tm.assert_frame_equal(result, expected)
27822782

2783+
def test_dataframe_from_array_like_with_name_attribute(self):
2784+
class DummyArray(np.ndarray):
2785+
def __new__(cls, input_array):
2786+
obj = np.asarray(input_array).view(cls)
2787+
obj.name = "foo"
2788+
return obj
2789+
2790+
dummy = DummyArray(np.eye(3))
2791+
df = DataFrame(dummy)
2792+
expected = DataFrame(np.eye(3))
2793+
tm.assert_frame_equal(df, expected)
27832794

27842795
class TestDataFrameConstructorIndexInference:
27852796
def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self):

0 commit comments

Comments
 (0)