Skip to content

Commit a86d008

Browse files
committed
BUG: support dtypes in column_dtypes for to_records()
1 parent 2fa0835 commit a86d008

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

pandas/core/frame.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1716,7 +1716,8 @@ def to_records(self, index=True, convert_datetime64=None,
17161716
# string naming a type.
17171717
if dtype_mapping is None:
17181718
formats.append(v.dtype)
1719-
elif isinstance(dtype_mapping, (type, compat.string_types)):
1719+
elif isinstance(dtype_mapping, (type, np.dtype,
1720+
compat.string_types)):
17201721
formats.append(dtype_mapping)
17211722
else:
17221723
element = "row" if i < index_len else "column"

pandas/tests/frame/test_convert_to.py

+23
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,29 @@ def test_to_records_dtype(self, kwargs, expected):
274274
result = df.to_records(**kwargs)
275275
tm.assert_almost_equal(result, expected)
276276

277+
@pytest.mark.parametrize("kwargs,expected", [
278+
# Pass in a dtype instance.
279+
(dict(column_dtypes=np.dtype('unicode')),
280+
np.rec.array([("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
281+
dtype=[("index", "<i8"), ("A", "<U"),
282+
("B", "<U"), ("C", "<U")])),
283+
284+
# Names / indices not in mapping default to array dtype.
285+
(dict(column_dtypes={"A": np.dtype('int8'), "B": np.dtype('float32')}),
286+
np.rec.array([("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")],
287+
dtype=[("index", "<i8"), ("A", "i1"),
288+
("B", "<f4"), ("C", "O")]))])
289+
def test_to_records_dtype_dtype(self, kwargs, expected):
290+
# See gh-24895
291+
df = DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]})
292+
293+
if isinstance(expected, str):
294+
with pytest.raises(ValueError, match=expected):
295+
df.to_records(**kwargs)
296+
else:
297+
result = df.to_records(**kwargs)
298+
tm.assert_almost_equal(result, expected)
299+
277300
@pytest.mark.parametrize("df,kwargs,expected", [
278301
# MultiIndex in the index.
279302
(DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],

0 commit comments

Comments
 (0)