From ae63852519b676a2c26f8c8ef4fc2ee2b1e4ef2b Mon Sep 17 00:00:00 2001 From: Christopher Whelan Date: Thu, 24 Jan 2019 00:10:20 -0800 Subject: [PATCH] BUG: support dtypes in column_dtypes for to_records() --- doc/source/whatsnew/v0.25.0.rst | 3 +-- pandas/core/frame.py | 3 ++- pandas/tests/frame/test_convert_to.py | 33 +++++++++++++++++++++++---- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index a9fa8b2174dd0..867007b2ba7f5 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -187,7 +187,7 @@ Reshaping ^^^^^^^^^ - Bug in :func:`merge` when merging by index name would sometimes result in an incorrectly numbered index (:issue:`24212`) -- +- :func:`to_records` now accepts dtypes to its `column_dtypes` parameter (:issue:`24895`) - @@ -213,4 +213,3 @@ Contributors ~~~~~~~~~~~~ .. contributors:: v0.24.x..HEAD - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 28c6f3c23a3ce..2049a8aa960bf 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1719,7 +1719,8 @@ def to_records(self, index=True, convert_datetime64=None, # string naming a type. if dtype_mapping is None: formats.append(v.dtype) - elif isinstance(dtype_mapping, (type, compat.string_types)): + elif isinstance(dtype_mapping, (type, np.dtype, + compat.string_types)): formats.append(dtype_mapping) else: element = "row" if i < index_len else "column" diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 7b98395dd6dec..601a4c6b72fe3 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -10,7 +10,9 @@ from pandas.compat import long -from pandas import DataFrame, MultiIndex, Series, Timestamp, compat, date_range +from pandas import ( + CategoricalDtype, DataFrame, MultiIndex, Series, Timestamp, compat, + date_range) from pandas.tests.frame.common import TestData import pandas.util.testing as tm @@ -220,6 +222,12 @@ def test_to_records_with_categorical(self): dtype=[("index", "