Skip to content

Commit 7b0714c

Browse files
jbrockmendelhweecat
authored andcommitted
BUG: pass 2D ndarray and EA-dtype to DataFrame, closes pandas-dev#12513 (pandas-dev#30507)
1 parent 10f415d commit 7b0714c

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
@@ -975,7 +975,8 @@ Other
975975
- Fixed ``pow`` operations for :class:`IntegerArray` when the other value is ``0`` or ``1`` (:issue:`29997`)
976976
- Bug in :meth:`Series.count` raises if use_inf_as_na is enabled (:issue:`29478`)
977977
- Bug in :class:`Index` where a non-hashable name could be set without raising ``TypeError`` (:issue:`29069`)
978-
978+
- Bug in :class:`DataFrame` constructor when passing a 2D ``ndarray`` and an extension dtype (:issue:`12513`)
979+
-
979980

980981
.. _whatsnew_1000.contributors:
981982

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
@@ -2553,3 +2553,11 @@ def test_from_tzaware_mixed_object_array(self):
25532553
"datetime64[ns, CET]",
25542554
]
25552555
assert (res.dtypes == expected_dtypes).all()
2556+
2557+
def test_from_2d_ndarray_with_dtype(self):
2558+
# GH#12513
2559+
array_dim2 = np.arange(10).reshape((5, 2))
2560+
df = pd.DataFrame(array_dim2, dtype="datetime64[ns, UTC]")
2561+
2562+
expected = pd.DataFrame(array_dim2).astype("datetime64[ns, UTC]")
2563+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)