当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python pandas.Index.union用法及代码示例

用法:

final Index.union(other, sort=None)

形成两个索引对象的并集。

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

参数

other索引或array-like
sort布尔或无,默认无

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

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

    1. selfother 相等。

    2. selfother 的长度为 0。

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

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

返回

union index

例子

联合匹配数据类型

>>> idx1 = pd.Index([1, 2, 3, 4])
>>> idx2 = pd.Index([3, 4, 5, 6])
>>> idx1.union(idx2)
Int64Index([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')],
   )

相关用法


注:本文由纯净天空筛选整理自pandas.pydata.org大神的英文原创作品 pandas.Index.union。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。