Skip to content

Commit 765d8db

Browse files
jbrockmendeljreback
authored andcommitted
BUG: pass 2D ndarray and EA-dtype to DataFrame, closes #12513 (#30507)
1 parent efaadd5 commit 765d8db

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

doc/source/whatsnew/v1.0.0.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -983,7 +983,8 @@ Other
983983
- Fixed ``pow`` operations for :class:`IntegerArray` when the other value is ``0`` or ``1`` (:issue:`29997`)
984984
- Bug in :meth:`Series.count` raises if use_inf_as_na is enabled (:issue:`29478`)
985985
- Bug in :class:`Index` where a non-hashable name could be set without raising ``TypeError`` (:issue:`29069`)
986-
986+
- Bug in :class:`DataFrame` constructor when passing a 2D ``ndarray`` and an extension dtype (:issue:`12513`)
987+
-
987988

988989
.. _whatsnew_1000.contributors:
989990

pandas/core/internals/construction.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,17 @@ def init_ndarray(values, index, columns, dtype=None, copy=False):
152152
return arrays_to_mgr([values], columns, index, columns, dtype=dtype)
153153
elif is_extension_array_dtype(values) or is_extension_array_dtype(dtype):
154154
# GH#19157
155+
156+
if isinstance(values, np.ndarray) and values.ndim > 1:
157+
# GH#12513 a EA dtype passed with a 2D array, split into
158+
# multiple EAs that view the values
159+
values = [values[:, n] for n in range(values.shape[1])]
160+
else:
161+
values = [values]
162+
155163
if columns is None:
156-
columns = [0]
157-
return arrays_to_mgr([values], columns, index, columns, dtype=dtype)
164+
columns = list(range(len(values)))
165+
return arrays_to_mgr(values, columns, index, columns, dtype=dtype)
158166

159167
# by definition an array here
160168
# the dtypes will be coerced to a single dtype

pandas/tests/frame/test_constructors.py

+8
Original file line numberDiff line numberDiff line change
@@ -2551,3 +2551,11 @@ def test_from_tzaware_mixed_object_array(self):
25512551
"datetime64[ns, CET]",
25522552
]
25532553
assert (res.dtypes == expected_dtypes).all()
2554+
2555+
def test_from_2d_ndarray_with_dtype(self):
2556+
# GH#12513
2557+
array_dim2 = np.arange(10).reshape((5, 2))
2558+
df = pd.DataFrame(array_dim2, dtype="datetime64[ns, UTC]")
2559+
2560+
expected = pd.DataFrame(array_dim2).astype("datetime64[ns, UTC]")
2561+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)