MCPcopy
hub / github.com/pandas-dev/pandas / ensure_index

Function ensure_index

pandas/core/indexes/base.py:7919–7975  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

7917
7918
7919def 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

Callers 15

_set_levelsMethod · 0.90
_get_combined_indexFunction · 0.90
_maybe_convert_i8Method · 0.90
__init__Method · 0.85
__init__Method · 0.85
from_recordsMethod · 0.85
_from_arraysMethod · 0.85
_init_mgrMethod · 0.85
_set_axisMethod · 0.85

Calls 3

IndexClass · 0.85
copyMethod · 0.45
from_arraysMethod · 0.45