Ensure that we have an index from some index-like object. Parameters ---------- index_like : sequence An Index or other sequence copy : bool, default False Returns ------- index : Index or MultiIndex See Also -------- ensure_index_from_sequence
(index_like: Axes, copy: bool = False)
| 7917 | |
| 7918 | |
| 7919 | def ensure_index(index_like: Axes, copy: bool = False) -> Index: |
| 7920 | """ |
| 7921 | Ensure that we have an index from some index-like object. |
| 7922 | |
| 7923 | Parameters |
| 7924 | ---------- |
| 7925 | index_like : sequence |
| 7926 | An Index or other sequence |
| 7927 | copy : bool, default False |
| 7928 | |
| 7929 | Returns |
| 7930 | ------- |
| 7931 | index : Index or MultiIndex |
| 7932 | |
| 7933 | See Also |
| 7934 | -------- |
| 7935 | ensure_index_from_sequences |
| 7936 | |
| 7937 | Examples |
| 7938 | -------- |
| 7939 | >>> ensure_index(["a", "b"]) |
| 7940 | Index(['a', 'b'], dtype='str') |
| 7941 | |
| 7942 | >>> ensure_index([("a", "a"), ("b", "c")]) |
| 7943 | Index([('a', 'a'), ('b', 'c')], dtype='object') |
| 7944 | |
| 7945 | >>> ensure_index([["a", "a"], ["b", "c"]]) |
| 7946 | MultiIndex([('a', 'b'), |
| 7947 | ('a', 'c')], |
| 7948 | ) |
| 7949 | """ |
| 7950 | if isinstance(index_like, Index): |
| 7951 | if copy: |
| 7952 | index_like = index_like.copy() |
| 7953 | return index_like |
| 7954 | |
| 7955 | if isinstance(index_like, ABCSeries): |
| 7956 | name = index_like.name |
| 7957 | return Index(index_like, name=name, copy=copy) |
| 7958 | |
| 7959 | if is_iterator(index_like): |
| 7960 | index_like = list(index_like) |
| 7961 | |
| 7962 | if isinstance(index_like, list): |
| 7963 | if type(index_like) is not list: |
| 7964 | # must check for exactly list here because of strict type |
| 7965 | # check in clean_index_list |
| 7966 | index_like = list(index_like) |
| 7967 | |
| 7968 | if index_like and lib.is_all_arraylike(index_like): |
| 7969 | from pandas.core.indexes.multi import MultiIndex |
| 7970 | |
| 7971 | return MultiIndex.from_arrays(index_like) |
| 7972 | else: |
| 7973 | return Index(index_like, copy=copy, tupleize_cols=False) |
| 7974 | else: |
| 7975 | return Index(index_like, copy=copy) |
| 7976 |