Skip to content

Accept CategoricalDtype in read_csv #17643

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Oct 2, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Doc and test unexpected values
  • Loading branch information
TomAugspurger committed Sep 26, 2017
commit 6f175a7f727d44cf819252d8979a38c1b19384b7
10 changes: 9 additions & 1 deletion doc/source/io.rst
Original file line number Diff line number Diff line change
Expand Up @@ -482,14 +482,22 @@ that column's ``dtype``.
dtype = CategoricalDtype(['d', 'c', 'b', 'a'], ordered=True)
pd.read_csv(StringIO(data), dtype={'col1': dtype}).dtypes

When using ``dtype=CategoricalDtype``, "unexpected" values outside of
``dtype.categories`` are treated as missing values.

dtype = CategoricalDtype(['a', 'b', 'd']) # No 'c'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing .. ipython:: python directive here

pd.read_csv(StringIO(data), dtype={'col1': dtype}).col1

This matches the behavior of :meth:`Categorical.set_categories`.

.. note::

With ``dtype='category'``, the resulting categories will always be parsed
as strings (object dtype). If the categories are numeric they can be
converted using the :func:`to_numeric` function, or as appropriate, another
converter such as :func:`to_datetime`.

When ``dtype`` is a ``CategoricalDtype`` with homogenous ``categoriess`` (
When ``dtype`` is a ``CategoricalDtype`` with homogenous ``categories`` (
all numeric, all datetimes, etc.), the conversion is done automatically.

.. ipython:: python
Expand Down
29 changes: 26 additions & 3 deletions doc/source/whatsnew/v0.21.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ expanded to include the ``categories`` and ``ordered`` attributes. A
``CategoricalDtype`` can be used to specify the set of categories and
orderedness of an array, independent of the data themselves. This can be useful,
e.g., when converting string data to a ``Categorical`` (:issue:`14711`,
:issue:`15078`, :issue:`16015`):
:issue:`15078`, :issue:`16015`, :issue:`17643`):

.. ipython:: python

Expand All @@ -129,8 +129,33 @@ e.g., when converting string data to a ``Categorical`` (:issue:`14711`,
dtype = CategoricalDtype(categories=['a', 'b', 'c', 'd'], ordered=True)
s.astype(dtype)

One place that deserves special mention is in :meth:`read_csv`. Previously, with
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe a separate sub-section for this

``dtype={'col': 'category'}``, the returned values and categories would always
be strings.

.. ipython:: python

from pandas.compat import StringIO
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in general we put this in the hidden code block at the top of the file, as people shouldn't use this from pandas, but just import it themselves


data = 'A,B\na,1\nb,2\nc,3'
pd.read_csv(StringIO(data), dtype={'B': 'category'}).B.cat.categories

Notice the "object" dtype.

With a ``CategoricalDtype`` of all numerics, datetimes, or
timedeltas, we can automatically convert to the correct type

dtype = {'B': CategoricalDtype([1, 2, 3])}
pd.read_csv(StringIO(data), dtype=dtype).B.cat.categories

The values have been correctly interpreted as integers.

The ``.dtype`` property of a ``Categorical``, ``CategoricalIndex`` or a
``Series`` with categorical type will now return an instance of ``CategoricalDtype``.
For the most part, this is backwards compatible, though the string repr has changed.
If you were previously using ``str(s.dtype == 'category')`` to detect categorical data,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing closing parenthesis around s.dtype (actually the closing one is in the wrong place)

switch to :func:`api.types.is_categorical_dtype`, which is compatible with the old and
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add pandas in the api.types.is_categorical_dtype

new ``CategoricalDtype``.

See the :ref:`CategoricalDtype docs <categorical.categoricaldtype>` for more.

Expand Down Expand Up @@ -163,8 +188,6 @@ Other Enhancements
- :func:`Categorical.rename_categories` now accepts a dict-like argument as `new_categories` and only updates the categories found in that dict. (:issue:`17336`)
- :func:`read_excel` raises ``ImportError`` with a better message if ``xlrd`` is not installed. (:issue:`17613`)
- :meth:`DataFrame.assign` will preserve the original order of ``**kwargs`` for Python 3.6+ users instead of sorting the column names
- Pass a :class:`~pandas.api.types.CategoricalDtype` to :meth:`read_csv` to parse categorical
data as numeric, datetimes, or timedeltas, instead of strings. See :ref:`here <io.categorical>`. (:issue:`17643`)


.. _whatsnew_0210.api_breaking:
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/io/parser/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,14 @@ def test_categoricaldtype_coerces_timedelta(self):
result = self.read_csv(StringIO(data), dtype=dtype)
tm.assert_frame_equal(result, expected)

def test_categoricaldtype_unexpected_categories(self):
dtype = {'b': CategoricalDtype(['a', 'b', 'd', 'e'])}
data = "b\nd\na\nc\nd" # Unexpected c
expected = pd.DataFrame({"b": Categorical(list('dacd'),
dtype=dtype['b'])})
result = self.read_csv(StringIO(data), dtype=dtype)
tm.assert_frame_equal(result, expected)

def test_categorical_categoricaldtype_chunksize(self):
# GH 10153
data = """a,b
Expand Down