Skip to content

API/ENH: union Categorical #13361

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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
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
15 changes: 15 additions & 0 deletions asv_bench/benchmarks/categoricals.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
from .pandas_vb_common import *
try:
from pandas.types.concat import union_categoricals
except ImportError:
pass
import string


Expand All @@ -12,6 +16,17 @@ def time_concat_categorical(self):
concat([self.s, self.s])


class union_categorical(object):
goal_time = 0.2

def setup(self):
self.a = pd.Categorical((list('aabbcd') * 1000000))
self.b = pd.Categorical((list('bbcdjk') * 1000000))

def time_union_categorical(self):
union_categoricals([self.a, self.b])


class categorical_value_counts(object):
goal_time = 1

Expand Down
23 changes: 23 additions & 0 deletions doc/source/categorical.rst
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,29 @@ In this case the categories are not the same and so an error is raised:

The same applies to ``df.append(df_different)``.

.. _categorical.union:

Unioning
~~~~~~~~

If you want to combine categoricals that do not necessarily have
Copy link
Contributor

Choose a reason for hiding this comment

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

versionadded tag here

the same categories, the `union_categorical` function will
combine a list-like of categoricals. The new categories
will be the union of the categories being combined.

.. ipython:: python

from pandas.types.concat import union_categoricals
a = pd.Categorical(["b", "c"])
b = pd.Categorical(["a", "b"])
union_categoricals([a, b])

.. note::

`union_categoricals` only works with unordered categoricals
and will raise if any are orderd.


Getting Data In/Out
-------------------

Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.18.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ Other enhancements

- The ``DataFrame`` constructor will now respect key ordering if a list of ``OrderedDict`` objects are passed in (:issue:`13304`)
- ``pd.read_html()`` has gained support for the ``decimal`` option (:issue:`12907`)

- A ``union_categorical`` function has been added for combining categoricals, see :ref:`Unioning Categoricals<categorical.union>` (:issue:`13361`)
- ``eval``'s upcasting rules for ``float32`` types have been updated to be more consistent with NumPy's rules. New behavior will not upcast to ``float64`` if you multiply a pandas ``float32`` object by a scalar float64. (:issue:`12388`)
- ``Series`` has gained the properties ``.is_monotonic``, ``.is_monotonic_increasing``, ``.is_monotonic_decreasing``, similar to ``Index`` (:issue:`13336`)

Expand Down
32 changes: 32 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -3943,6 +3943,38 @@ def f():
'category', categories=list('cab'))})
tm.assert_frame_equal(result, expected)

def test_union(self):
Copy link
Contributor

Choose a reason for hiding this comment

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

does that belong to the concat tests or the categoricals? The API is in concat and not in Categorical (which I like... :-) )

Copy link
Contributor

Choose a reason for hiding this comment

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

yeah it could go there

from pandas.types.concat import union_categoricals

s = Categorical(list('abc'))
s2 = Categorical(list('abd'))
result = union_categoricals([s, s2])
expected = Categorical(list('abcabd'))
tm.assert_categorical_equal(result, expected, ignore_order=True)

s = Categorical([0,1,2])
s2 = Categorical([2,3,4])
result = union_categoricals([s, s2])
expected = Categorical([0,1,2,2,3,4])
tm.assert_categorical_equal(result, expected, ignore_order=True)

s = Categorical([0,1.2,2])
s2 = Categorical([2,3.4,4])
result = union_categoricals([s, s2])
expected = Categorical([0,1.2,2,2,3.4,4])
tm.assert_categorical_equal(result, expected, ignore_order=True)

# can't be ordered
s = Categorical([0,1.2,2], ordered=True)
with tm.assertRaises(TypeError):
union_categoricals([s, s2])

# must exactly match types
s = Categorical([0,1.2,2])
s2 = Categorical([2,3,4])
with tm.assertRaises(TypeError):
union_categoricals([s, s2])

def test_categorical_index_preserver(self):

a = Series(np.arange(6, dtype='int64'))
Expand Down
40 changes: 40 additions & 0 deletions pandas/types/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,46 @@ def convert_categorical(x):
return Categorical(concatted, rawcats)


def union_categoricals(to_union):
Copy link
Contributor

Choose a reason for hiding this comment

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

Add a ignore_order=False kwarg? That would prevent changed/copied orig categoricals if you ever need this... Would only disable the order check

if not ignore_order and any(c.ordered for c in to_union):
        raise TypeError("Can only combine unordered Categoricals")

It would still return a unordered cat, of course.

"""
Copy link
Contributor

Choose a reason for hiding this comment

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

add a versionadded tag

Combine list-like of Categoricals, unioning categories. All
must have the same dtype, and none can be ordered.

Parameters
----------
to_union : list like of Categorical

Copy link
Contributor

Choose a reason for hiding this comment

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

add Raises (and list when that happens)

Returns
-------
Categorical
A single array, categories will be ordered as they
appear in the list
"""
from pandas import Index, Categorical

if any(c.ordered for c in to_union):
raise TypeError("Can only combine unordered Categoricals")

first = to_union[0]
Copy link
Member

Choose a reason for hiding this comment

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

You should graceful catch the condition that the list of categoricals is empty.

if not all(com.is_dtype_equal(c.categories, first.categories)
for c in to_union):
raise TypeError("dtype of categories must be the same")

for i, c in enumerate(to_union):
if i == 0:
cats = c.categories.tolist()
Copy link
Member

@shoyer shoyer Jun 6, 2016

Choose a reason for hiding this comment

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

Use numpy arrays (or pandas indexes) and concatenate them all at once rather than converting things into lists. Something like:

cats = to_union[0].categories
appended_cats = cats.append([c.categories for c in to_union[1:]])
unique_cats = appended_cats.unique()

In the worst case, suppose you have n categoricals of fixed size, each of which has all unique values.

My version takes linear time (and space), whereas your version will require quadratic time -- n index/hash table constructions of O(n) elements each, on average.

Copy link
Contributor

Choose a reason for hiding this comment

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

you soln won't preseve order, though with a small mod I think it could, need to np.concatenate the categories directly (that's why they were listifed in the first place). Index union doesn't preserve order.

Copy link
Contributor

Choose a reason for hiding this comment

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

though to be honest I can't imagine this is a perf issue. The entire point of this is that categories is << codes. But I suppose if it can be done with no additional complexity then it should.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks @shoyer. I didn't know pd.unique preserves order (numpy sorts), but seems to be the case. Is that an api guarantee?

In [12]: pd.Index(['b','c']).append(pd.Index(['a'])).unique()
Out[12]: array(['b', 'c', 'a'], dtype=object)

Copy link
Contributor

Choose a reason for hiding this comment

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

@chris-b1 yes it IS a guarantee (and that's why its much faster than np.unique)

else:
cats = cats + c.categories.difference(Index(cats)).tolist()

cats = Index(cats)
new_codes = []
for c in to_union:
indexer = cats.get_indexer(c.categories)
new_codes.append(indexer.take(c.codes))
codes = np.concatenate(new_codes)
return Categorical.from_codes(codes, cats)
Copy link
Contributor

Choose a reason for hiding this comment

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

This still does a validation, maybe change to use the fastpath way? Categorical(codes, categories=categories, ordered=False, fastpath=True)

Copy link
Contributor

Choose a reason for hiding this comment

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

maybe we should add a validate=True flag to .from_codes to (optionally) skip the validation?

Copy link
Contributor

Choose a reason for hiding this comment

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

Basically you would just end up doing two if fastpath checks right after another (first "from_codes, then ininit)...fastpath=True` is deep internal stuff, so why not use the constructor as intended?



def _concat_datetime(to_concat, axis=0, typs=None):
"""
provide concatenation of an datetimelike array of arrays each of which is a
Expand Down
11 changes: 8 additions & 3 deletions pandas/util/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -963,12 +963,17 @@ def assertNotIsInstance(obj, cls, msg=''):


def assert_categorical_equal(left, right, check_dtype=True,
obj='Categorical'):
obj='Categorical', ignore_order=False):
assertIsInstance(left, pd.Categorical, '[Categorical] ')
Copy link
Contributor

Choose a reason for hiding this comment

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

can you add a doc-string

assertIsInstance(right, pd.Categorical, '[Categorical] ')

assert_index_equal(left.categories, right.categories,
obj='{0}.categories'.format(obj))
if ignore_order:
assert_index_equal(left.categories.sort_values(),
right.categories.sort_values(),
obj='{0}.categories'.format(obj))
else:
assert_index_equal(left.categories, right.categories,
obj='{0}.categories'.format(obj))
assert_numpy_array_equal(left.codes, right.codes, check_dtype=check_dtype,
obj='{0}.codes'.format(obj))

Expand Down