Skip to content

Commit 597cfb8

Browse files
committed
fix calling in ensure_string_array
1 parent db1020c commit 597cfb8

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

pandas/core/construction.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,15 @@ def _try_cast(
786786

787787
elif dtype.kind == "U":
788788
# TODO: test cases with arr.dtype.kind in ["m", "M"]
789-
return lib.ensure_string_array(arr, convert_na_value=False, copy=copy)
789+
if is_ndarray:
790+
shape = arr.shape
791+
if arr.ndim > 1:
792+
arr = arr.ravel()
793+
else:
794+
shape = (len(arr),)
795+
return lib.ensure_string_array(arr, convert_na_value=False, copy=copy).reshape(
796+
shape
797+
)
790798

791799
elif dtype.kind in ["m", "M"]:
792800
return maybe_cast_to_datetime(arr, dtype)

pandas/tests/frame/test_constructors.py

+8
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,14 @@
7070

7171

7272
class TestDataFrameConstructors:
73+
def test_constructor_from_ndarray_with_str_dtype(self):
74+
# If we don't ravel/reshape around ensure_str_array, we end up
75+
# with an array of strings each of which is e.g. "[0 1 2]"
76+
arr = np.arange(12).reshape(4, 3)
77+
df = DataFrame(arr, dtype=str)
78+
expected = DataFrame(arr.astype(str))
79+
tm.assert_frame_equal(df, expected)
80+
7381
def test_constructor_from_2d_datetimearray(self, using_array_manager):
7482
dti = date_range("2016-01-01", periods=6, tz="US/Pacific")
7583
dta = dti._data.reshape(3, 2)

0 commit comments

Comments
 (0)