pandas.api.types.union_categoricals#

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

将类似分类的联合类别的列表组合在一起。

所有类别必须具有相同的数据类型。

参数
to_union列表式

类别、类别索引或具有dtype=‘CATEGORY’的系列。

sort_categories布尔值,默认为False

如果为True,则将对生成的类别进行词法排序,否则将按照它们在数据中出现的顺序进行排序。

ignore_order布尔值,默认为False

如果为True,则将忽略类别的已排序属性。结果会导致一个无序的分类。

退货
直截了当的
加薪
TypeError
  • 所有输入的数据类型并不相同

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

  • 所有输入都是有序的,并且它们的类别并不相同

  • SORT_CATEGORIES=True和分类已排序

ValueError

传递的类别列表为空

注意事项

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

示例

如果您想组合不一定具有相同类别的范畴词, union_categoricals 将结合一组类似于分类词的列表。新的类别将是正在合并的类别的联合。

>>> 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 也适用于组合相同类别和订单信息的两个类别的情况(例如,您还可以 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

0.20.0版中的新增功能

具有不同类别或排序的已排序类别可以使用 ignore_ordered=True 论点。

>>> 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 also works with a CategoricalIndex, or Series containing categorical data, but note that the resulting array will always be a plain 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']