pandas.Index.union #

最终 索引。union ( other , sort = None ) [来源] #

形成两个 Index 对象的并集。

如果 Index 对象不兼容,两个 Index 对象将首先转换为 dtype('object')。

参数
其他索引或类似数组
排序bool 或 None,默认 None

是否对结果索引进行排序。

  • None :对结果进行排序,除非

    1. 自我他人是平等的。

    2. selfother 的长度为 0。

    3. selfother 的某些值无法进行比较。在这种情况下会发出 RuntimeWarning。

  • False :不对结果进行排序。

  • True :对结果进行排序(这可能会引发 TypeError)。

返回
指数

例子

联合匹配数据类型

>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([3, 4, 5, 6])
>>> idx1.union(idx2)
Index([1, 2, 3, 4, 5, 6], dtype='int64')

联合不匹配的数据类型

>>> idx1 = pd.Index(['a', 'b', 'c', 'd'])
>>> idx2 = pd.Index([1, 2, 3, 4])
>>> idx1.union(idx2)
Index(['a', 'b', 'c', 'd', 1, 2, 3, 4], dtype='object')

多索引案例

>>> idx1 = pd.MultiIndex.from_arrays(
...     [[1, 1, 2, 2], ["Red", "Blue", "Red", "Blue"]]
... )
>>> idx1
MultiIndex([(1,  'Red'),
    (1, 'Blue'),
    (2,  'Red'),
    (2, 'Blue')],
   )
>>> idx2 = pd.MultiIndex.from_arrays(
...     [[3, 3, 2, 2], ["Red", "Green", "Red", "Green"]]
... )
>>> idx2
MultiIndex([(3,   'Red'),
    (3, 'Green'),
    (2,   'Red'),
    (2, 'Green')],
   )
>>> idx1.union(idx2)
MultiIndex([(1,  'Blue'),
    (1,   'Red'),
    (2,  'Blue'),
    (2, 'Green'),
    (2,   'Red'),
    (3, 'Green'),
    (3,   'Red')],
   )
>>> idx1.union(idx2, sort=False)
MultiIndex([(1,   'Red'),
    (1,  'Blue'),
    (2,   'Red'),
    (2,  'Blue'),
    (3,   'Red'),
    (3, 'Green'),
    (2, 'Green')],
   )