pandas.Index.union#
- final Index.union(other, sort=None)[源代码]#
形成两个 Index 对象的并集。
如果 Index 对象不兼容,则首先将两个 Index 对象都强制转换为 dtype(‘object’)。
- Parameters:
- otherIndex 或类数组
- sortbool 或 None,default None
是否对生成的 Index 进行排序。
None :对结果进行排序,除非
self 和 other 相等。
self 或 other 的长度为 0。
self 或 other 中的某些值无法比较。在这种情况下会发出 RuntimeWarning。
False : 不对结果进行排序。
True : 对结果进行排序(这可能会引发 TypeError)。
- Returns:
- pandas.DataFrame.keys
Examples
联合匹配的 dtype
>>> 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')
联合不匹配的 dtype
>>> 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')
MultiIndex 情况
>>> 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')], )