pandas.api.types.union_categoricals#

pandas.api.types.union_categoricals(to_union, sort_categories=False, ignore_order=False)[源代码]#

组合列表式的 Categorical 对象,并联合类别。

所有类别必须具有相同的 dtype。

Parameters:
to_union类似列表

Categorical、CategoricalIndex 或 dtype 为 ‘category’ 的 Series。

sort_categoriesbool,默认 False

如果为 True,则结果类别将按字母顺序排序,否则它们将按数据中出现的顺序排列。

ignore_orderbool,默认 False

如果为 True,则将忽略 Categoricals 的 ordered 属性。结果将是一个无序的 categorical。

Returns:
Categorical
Raises:
TypeError
  • 所有输入不具有相同的 dtype

  • 所有输入不具有相同的 ordered 属性

  • 所有输入都已排序但类别不相同

  • sort_categories=True 且 Categoricals 已排序

ValueError

传递了空的 categorical 列表

Notes

要了解有关类别的更多信息,请参阅 link

Examples

如果您想组合不一定具有相同类别的 categories,union_categoricals 将组合一个列表式的 categories。新类别将是被组合的类别的并集。

>>> a = pd.Categorical(["b", "c"])
>>> b = pd.Categorical(["a", "b"])
>>> pd.api.types.union_categoricals([a, b])
['b', 'c', 'a', 'b']
Categories (3, object): ['b', 'c', 'a']

默认情况下,结果类别将按其在数据 categories 中出现的顺序排序。如果您希望类别按字母顺序排序,请使用 sort_categories=True 参数。

>>> pd.api.types.union_categoricals([a, b], sort_categories=True)
['b', 'c', 'a', 'b']
Categories (3, object): ['a', 'b', 'c']

union_categoricals 也适用于组合具有相同类别和顺序信息的两个 categories 的情况(例如,您也可以 append 的情况)。

>>> a = pd.Categorical(["a", "b"], ordered=True)
>>> b = pd.Categorical(["a", "b", "a"], ordered=True)
>>> pd.api.types.union_categoricals([a, b])
['a', 'b', 'a', 'b', 'a']
Categories (2, object): ['a' < 'b']

由于类别已排序且不相同,因此引发 TypeError

>>> a = pd.Categorical(["a", "b"], ordered=True)
>>> b = pd.Categorical(["a", "b", "c"], ordered=True)
>>> pd.api.types.union_categoricals([a, b])
Traceback (most recent call last):
    ...
TypeError: to union ordered Categoricals, all categories must be the same

通过使用 ignore_ordered=True 参数,可以组合具有不同类别或顺序的已排序 categories。

>>> a = pd.Categorical(["a", "b", "c"], ordered=True)
>>> b = pd.Categorical(["c", "b", "a"], ordered=True)
>>> pd.api.types.union_categoricals([a, b], ignore_order=True)
['a', 'b', 'c', 'c', 'b', 'a']
Categories (3, object): ['a', 'b', 'c']

union_categoricals 也适用于 CategoricalIndex 或包含 categorical 数据的 Series,但请注意,结果数组将始终是一个普通的 Categorical

>>> a = pd.Series(["b", "c"], dtype='category')
>>> b = pd.Series(["a", "b"], dtype='category')
>>> pd.api.types.union_categoricals([a, b])
['b', 'c', 'a', 'b']
Categories (3, object): ['b', 'c', 'a']