Form the union of two Index objects. If the Index objects are incompatible, both Index objects will be cast to dtype('object') first. Parameters ---------- other : Index or array-like Index or an array-like object containing elements to
(self, other, sort: bool | None = None)
| 3023 | |
| 3024 | @final |
| 3025 | def union(self, other, sort: bool | None = None): |
| 3026 | """ |
| 3027 | Form the union of two Index objects. |
| 3028 | |
| 3029 | If the Index objects are incompatible, both Index objects will be |
| 3030 | cast to dtype('object') first. |
| 3031 | |
| 3032 | Parameters |
| 3033 | ---------- |
| 3034 | other : Index or array-like |
| 3035 | Index or an array-like object containing elements to form the union |
| 3036 | with the original Index. |
| 3037 | sort : bool or None, default None |
| 3038 | Whether to sort the resulting Index. |
| 3039 | |
| 3040 | * None : Sort the result, except when |
| 3041 | |
| 3042 | 1. `self` and `other` are equal. |
| 3043 | 2. `self` or `other` has length 0. |
| 3044 | 3. Some values in `self` or `other` cannot be compared. |
| 3045 | A RuntimeWarning is issued in this case. |
| 3046 | |
| 3047 | * False : do not sort the result. |
| 3048 | * True : Sort the result (which may raise TypeError). |
| 3049 | |
| 3050 | Returns |
| 3051 | ------- |
| 3052 | Index |
| 3053 | Returns a new Index object with all unique elements from both the original |
| 3054 | Index and the `other` Index. |
| 3055 | |
| 3056 | See Also |
| 3057 | -------- |
| 3058 | Index.unique : Return unique values in the index. |
| 3059 | Index.intersection : Form the intersection of two Index objects. |
| 3060 | Index.difference : Return a new Index with elements of index not in `other`. |
| 3061 | |
| 3062 | Examples |
| 3063 | -------- |
| 3064 | Union matching dtypes |
| 3065 | |
| 3066 | >>> idx1 = pd.Index([1, 2, 3, 4]) |
| 3067 | >>> idx2 = pd.Index([3, 4, 5, 6]) |
| 3068 | >>> idx1.union(idx2) |
| 3069 | Index([1, 2, 3, 4, 5, 6], dtype='int64') |
| 3070 | |
| 3071 | Union mismatched dtypes |
| 3072 | |
| 3073 | >>> idx1 = pd.Index(["a", "b", "c", "d"]) |
| 3074 | >>> idx2 = pd.Index([1, 2, 3, 4]) |
| 3075 | >>> idx1.union(idx2) |
| 3076 | Index(['a', 'b', 'c', 'd', 1, 2, 3, 4], dtype='object') |
| 3077 | |
| 3078 | MultiIndex case |
| 3079 | |
| 3080 | >>> idx1 = pd.MultiIndex.from_arrays( |
| 3081 | ... [[1, 1, 2, 2], ["Red", "Blue", "Red", "Blue"]] |
| 3082 | ... ) |