doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
pandas.Index.append Index.append(other)[source] Append a collection of Index options together. Parameters other:Index or list/tuple of indices Returns Index
pandas.reference.api.pandas.index.append
pandas.Index.argmax Index.argmax(axis=None, skipna=True, *args, **kwargs)[source] Return int position of the largest value in the Series. If the maximum is achieved in multiple locations, the first row position is returned. Parameters axis:{None} Dummy argument for consistency with Series. skipna:bool, default True Exclude NA/null values when showing the result. *args, **kwargs Additional arguments and keywords for compatibility with NumPy. Returns int Row position of the maximum value. See also Series.argmax Return position of the maximum value. Series.argmin Return position of the minimum value. numpy.ndarray.argmax Equivalent method for numpy arrays. Series.idxmax Return index label of the maximum values. Series.idxmin Return index label of the minimum values. Examples Consider dataset containing cereal calories >>> s = pd.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0, ... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}) >>> s Corn Flakes 100.0 Almond Delight 110.0 Cinnamon Toast Crunch 120.0 Cocoa Puff 110.0 dtype: float64 >>> s.argmax() 2 >>> s.argmin() 0 The maximum cereal calories is the third element and the minimum cereal calories is the first element, since series is zero-indexed.
pandas.reference.api.pandas.index.argmax
pandas.Index.argmin Index.argmin(axis=None, skipna=True, *args, **kwargs)[source] Return int position of the smallest value in the Series. If the minimum is achieved in multiple locations, the first row position is returned. Parameters axis:{None} Dummy argument for consistency with Series. skipna:bool, default True Exclude NA/null values when showing the result. *args, **kwargs Additional arguments and keywords for compatibility with NumPy. Returns int Row position of the minimum value. See also Series.argmin Return position of the minimum value. Series.argmax Return position of the maximum value. numpy.ndarray.argmin Equivalent method for numpy arrays. Series.idxmax Return index label of the maximum values. Series.idxmin Return index label of the minimum values. Examples Consider dataset containing cereal calories >>> s = pd.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0, ... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}) >>> s Corn Flakes 100.0 Almond Delight 110.0 Cinnamon Toast Crunch 120.0 Cocoa Puff 110.0 dtype: float64 >>> s.argmax() 2 >>> s.argmin() 0 The maximum cereal calories is the third element and the minimum cereal calories is the first element, since series is zero-indexed.
pandas.reference.api.pandas.index.argmin
pandas.Index.argsort Index.argsort(*args, **kwargs)[source] Return the integer indices that would sort the index. Parameters *args Passed to numpy.ndarray.argsort. **kwargs Passed to numpy.ndarray.argsort. Returns np.ndarray[np.intp] Integer indices that would sort the index if used as an indexer. See also numpy.argsort Similar method for NumPy arrays. Index.sort_values Return sorted copy of Index. Examples >>> idx = pd.Index(['b', 'a', 'd', 'c']) >>> idx Index(['b', 'a', 'd', 'c'], dtype='object') >>> order = idx.argsort() >>> order array([1, 0, 3, 2]) >>> idx[order] Index(['a', 'b', 'c', 'd'], dtype='object')
pandas.reference.api.pandas.index.argsort
pandas.Index.array Index.array The ExtensionArray of the data backing this Series or Index. Returns ExtensionArray An ExtensionArray of the values stored within. For extension types, this is the actual array. For NumPy native types, this is a thin (no copy) wrapper around numpy.ndarray. .array differs .values which may require converting the data to a different form. See also Index.to_numpy Similar method that always returns a NumPy array. Series.to_numpy Similar method that always returns a NumPy array. Notes This table lays out the different array types for each extension dtype within pandas. dtype array type category Categorical period PeriodArray interval IntervalArray IntegerNA IntegerArray string StringArray boolean BooleanArray datetime64[ns, tz] DatetimeArray For any 3rd-party extension types, the array type will be an ExtensionArray. For all remaining dtypes .array will be a arrays.NumpyExtensionArray wrapping the actual ndarray stored within. If you absolutely need a NumPy array (possibly with copying / coercing data), then use Series.to_numpy() instead. Examples For regular NumPy types like int, and float, a PandasArray is returned. >>> pd.Series([1, 2, 3]).array <PandasArray> [1, 2, 3] Length: 3, dtype: int64 For extension types, like Categorical, the actual ExtensionArray is returned >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) >>> ser.array ['a', 'b', 'a'] Categories (2, object): ['a', 'b']
pandas.reference.api.pandas.index.array
pandas.Index.asi8 propertyIndex.asi8 Integer representation of the values. Returns ndarray An ndarray with int64 dtype.
pandas.reference.api.pandas.index.asi8
pandas.Index.asof finalIndex.asof(label)[source] Return the label from the index, or, if not present, the previous one. Assuming that the index is sorted, return the passed index label if it is in the index, or return the previous index label if the passed one is not in the index. Parameters label:object The label up to which the method returns the latest index label. Returns object The passed label if it is in the index. The previous label if the passed label is not in the sorted index or NaN if there is no such label. See also Series.asof Return the latest value in a Series up to the passed index. merge_asof Perform an asof merge (similar to left join but it matches on nearest key rather than equal key). Index.get_loc An asof is a thin wrapper around get_loc with method=’pad’. Examples Index.asof returns the latest index label up to the passed label. >>> idx = pd.Index(['2013-12-31', '2014-01-02', '2014-01-03']) >>> idx.asof('2014-01-01') '2013-12-31' If the label is in the index, the method returns the passed label. >>> idx.asof('2014-01-02') '2014-01-02' If all of the labels in the index are later than the passed label, NaN is returned. >>> idx.asof('1999-01-02') nan If the index is not sorted, an error is raised. >>> idx_not_sorted = pd.Index(['2013-12-31', '2015-01-02', ... '2014-01-03']) >>> idx_not_sorted.asof('2013-12-31') Traceback (most recent call last): ValueError: index must be monotonic increasing or decreasing
pandas.reference.api.pandas.index.asof
pandas.Index.asof_locs Index.asof_locs(where, mask)[source] Return the locations (indices) of labels in the index. As in the asof function, if the label (a particular entry in where) is not in the index, the latest index label up to the passed label is chosen and its index returned. If all of the labels in the index are later than a label in where, -1 is returned. mask is used to ignore NA values in the index during calculation. Parameters where:Index An Index consisting of an array of timestamps. mask:np.ndarray[bool] Array of booleans denoting where values in the original data are not NA. Returns np.ndarray[np.intp] An array of locations (indices) of the labels from the Index which correspond to the return values of the asof function for every element in where.
pandas.reference.api.pandas.index.asof_locs
pandas.Index.astype Index.astype(dtype, copy=True)[source] Create an Index with values cast to dtypes. The class of a new Index is determined by dtype. When conversion is impossible, a TypeError exception is raised. Parameters dtype:numpy dtype or pandas type Note that any signed integer dtype is treated as 'int64', and any unsigned integer dtype is treated as 'uint64', regardless of the size. copy:bool, default True By default, astype always returns a newly allocated object. If copy is set to False and internal requirements on dtype are satisfied, the original data is used to create a new Index or the original Index is returned. Returns Index Index with values cast to specified dtype.
pandas.reference.api.pandas.index.astype
pandas.Index.copy Index.copy(name=None, deep=False, dtype=None, names=None)[source] Make a copy of this object. Name and dtype sets those attributes on the new object. Parameters name:Label, optional Set name for new object. deep:bool, default False dtype:numpy dtype or pandas type, optional Set dtype for new object. Deprecated since version 1.2.0: use astype method instead. names:list-like, optional Kept for compatibility with MultiIndex. Should not be used. Deprecated since version 1.4.0: use name instead. Returns Index Index refer to new object which is a copy of this object. Notes In most cases, there should be no functional difference from using deep, but if deep is passed it will attempt to deepcopy.
pandas.reference.api.pandas.index.copy
pandas.Index.delete Index.delete(loc)[source] Make new Index with passed location(-s) deleted. Parameters loc:int or list of int Location of item(-s) which will be deleted. Use a list of locations to delete more than one value at the same time. Returns Index Will be same type as self, except for RangeIndex. See also numpy.delete Delete any rows and column from NumPy array (ndarray). Examples >>> idx = pd.Index(['a', 'b', 'c']) >>> idx.delete(1) Index(['a', 'c'], dtype='object') >>> idx = pd.Index(['a', 'b', 'c']) >>> idx.delete([0, 2]) Index(['b'], dtype='object')
pandas.reference.api.pandas.index.delete
pandas.Index.difference finalIndex.difference(other, sort=None)[source] Return a new Index with elements of index not in other. This is the set difference of two Index objects. Parameters other:Index or array-like sort:False or None, default None Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. False : Do not sort the result. Returns difference:Index Examples >>> idx1 = pd.Index([2, 1, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.difference(idx2) Int64Index([1, 2], dtype='int64') >>> idx1.difference(idx2, sort=False) Int64Index([2, 1], dtype='int64')
pandas.reference.api.pandas.index.difference
pandas.Index.drop Index.drop(labels, errors='raise')[source] Make new Index with passed list of labels deleted. Parameters labels:array-like or scalar errors:{‘ignore’, ‘raise’}, default ‘raise’ If ‘ignore’, suppress error and existing labels are dropped. Returns dropped:Index Will be same type as self, except for RangeIndex. Raises KeyError If not all of the labels are found in the selected axis
pandas.reference.api.pandas.index.drop
pandas.Index.drop_duplicates Index.drop_duplicates(keep='first')[source] Return Index with duplicate values removed. Parameters keep:{‘first’, ‘last’, False}, default ‘first’ ‘first’ : Drop duplicates except for the first occurrence. ‘last’ : Drop duplicates except for the last occurrence. False : Drop all duplicates. Returns deduplicated:Index See also Series.drop_duplicates Equivalent method on Series. DataFrame.drop_duplicates Equivalent method on DataFrame. Index.duplicated Related method on Index, indicating duplicate Index values. Examples Generate an pandas.Index with duplicate values. >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama', 'hippo']) The keep parameter controls which duplicate values are removed. The value ‘first’ keeps the first occurrence for each set of duplicated entries. The default value of keep is ‘first’. >>> idx.drop_duplicates(keep='first') Index(['lama', 'cow', 'beetle', 'hippo'], dtype='object') The value ‘last’ keeps the last occurrence for each set of duplicated entries. >>> idx.drop_duplicates(keep='last') Index(['cow', 'beetle', 'lama', 'hippo'], dtype='object') The value False discards all sets of duplicated entries. >>> idx.drop_duplicates(keep=False) Index(['cow', 'beetle', 'hippo'], dtype='object')
pandas.reference.api.pandas.index.drop_duplicates
pandas.Index.droplevel finalIndex.droplevel(level=0)[source] Return index with requested level(s) removed. If resulting index has only 1 level left, the result will be of Index type, not MultiIndex. Parameters level:int, str, or list-like, default 0 If a string is given, must be the name of a level If list-like, elements must be names or indexes of levels. Returns Index or MultiIndex Examples >>> mi = pd.MultiIndex.from_arrays( ... [[1, 2], [3, 4], [5, 6]], names=['x', 'y', 'z']) >>> mi MultiIndex([(1, 3, 5), (2, 4, 6)], names=['x', 'y', 'z']) >>> mi.droplevel() MultiIndex([(3, 5), (4, 6)], names=['y', 'z']) >>> mi.droplevel(2) MultiIndex([(1, 3), (2, 4)], names=['x', 'y']) >>> mi.droplevel('z') MultiIndex([(1, 3), (2, 4)], names=['x', 'y']) >>> mi.droplevel(['x', 'y']) Int64Index([5, 6], dtype='int64', name='z')
pandas.reference.api.pandas.index.droplevel
pandas.Index.dropna Index.dropna(how='any')[source] Return Index without NA/NaN values. Parameters how:{‘any’, ‘all’}, default ‘any’ If the Index is a MultiIndex, drop the value when any or all levels are NaN. Returns Index
pandas.reference.api.pandas.index.dropna
pandas.Index.dtype Index.dtype Return the dtype object of the underlying data.
pandas.reference.api.pandas.index.dtype
pandas.Index.duplicated Index.duplicated(keep='first')[source] Indicate duplicate index values. Duplicated values are indicated as True values in the resulting array. Either all duplicates, all except the first, or all except the last occurrence of duplicates can be indicated. Parameters keep:{‘first’, ‘last’, False}, default ‘first’ The value or values in a set of duplicates to mark as missing. ‘first’ : Mark duplicates as True except for the first occurrence. ‘last’ : Mark duplicates as True except for the last occurrence. False : Mark all duplicates as True. Returns np.ndarray[bool] See also Series.duplicated Equivalent method on pandas.Series. DataFrame.duplicated Equivalent method on pandas.DataFrame. Index.drop_duplicates Remove duplicate values from Index. Examples By default, for each set of duplicated values, the first occurrence is set to False and all others to True: >>> idx = pd.Index(['lama', 'cow', 'lama', 'beetle', 'lama']) >>> idx.duplicated() array([False, False, True, False, True]) which is equivalent to >>> idx.duplicated(keep='first') array([False, False, True, False, True]) By using ‘last’, the last occurrence of each set of duplicated values is set on False and all others on True: >>> idx.duplicated(keep='last') array([ True, False, True, False, False]) By setting keep on False, all duplicates are True: >>> idx.duplicated(keep=False) array([ True, False, True, False, True])
pandas.reference.api.pandas.index.duplicated
pandas.Index.empty propertyIndex.empty
pandas.reference.api.pandas.index.empty
pandas.Index.equals Index.equals(other)[source] Determine if two Index object are equal. The things that are being compared are: The elements inside the Index object. The order of the elements inside the Index object. Parameters other:Any The other object to compare against. Returns bool True if “other” is an Index and it has the same elements and order as the calling index; False otherwise. Examples >>> idx1 = pd.Index([1, 2, 3]) >>> idx1 Int64Index([1, 2, 3], dtype='int64') >>> idx1.equals(pd.Index([1, 2, 3])) True The elements inside are compared >>> idx2 = pd.Index(["1", "2", "3"]) >>> idx2 Index(['1', '2', '3'], dtype='object') >>> idx1.equals(idx2) False The order is compared >>> ascending_idx = pd.Index([1, 2, 3]) >>> ascending_idx Int64Index([1, 2, 3], dtype='int64') >>> descending_idx = pd.Index([3, 2, 1]) >>> descending_idx Int64Index([3, 2, 1], dtype='int64') >>> ascending_idx.equals(descending_idx) False The dtype is not compared >>> int64_idx = pd.Int64Index([1, 2, 3]) >>> int64_idx Int64Index([1, 2, 3], dtype='int64') >>> uint64_idx = pd.UInt64Index([1, 2, 3]) >>> uint64_idx UInt64Index([1, 2, 3], dtype='uint64') >>> int64_idx.equals(uint64_idx) True
pandas.reference.api.pandas.index.equals
pandas.Index.factorize Index.factorize(sort=False, na_sentinel=- 1)[source] Encode the object as an enumerated type or categorical variable. This method is useful for obtaining a numeric representation of an array when all that matters is identifying distinct values. factorize is available as both a top-level function pandas.factorize(), and as a method Series.factorize() and Index.factorize(). Parameters sort:bool, default False Sort uniques and shuffle codes to maintain the relationship. na_sentinel:int or None, default -1 Value to mark “not found”. If None, will not drop the NaN from the uniques of the values. Changed in version 1.1.2. Returns codes:ndarray An integer ndarray that’s an indexer into uniques. uniques.take(codes) will have the same values as values. uniques:ndarray, Index, or Categorical The unique valid values. When values is Categorical, uniques is a Categorical. When values is some other pandas object, an Index is returned. Otherwise, a 1-D ndarray is returned. Note Even if there’s a missing value in values, uniques will not contain an entry for it. See also cut Discretize continuous-valued array. unique Find the unique value in an array. Examples These examples all show factorize as a top-level method like pd.factorize(values). The results are identical for methods like Series.factorize(). >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b']) >>> codes array([0, 0, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object) With sort=True, the uniques will be sorted, and codes will be shuffled so that the relationship is the maintained. >>> codes, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'], sort=True) >>> codes array([1, 1, 0, 2, 1]...) >>> uniques array(['a', 'b', 'c'], dtype=object) Missing values are indicated in codes with na_sentinel (-1 by default). Note that missing values are never included in uniques. >>> codes, uniques = pd.factorize(['b', None, 'a', 'c', 'b']) >>> codes array([ 0, -1, 1, 2, 0]...) >>> uniques array(['b', 'a', 'c'], dtype=object) Thus far, we’ve only factorized lists (which are internally coerced to NumPy arrays). When factorizing pandas objects, the type of uniques will differ. For Categoricals, a Categorical is returned. >>> cat = pd.Categorical(['a', 'a', 'c'], categories=['a', 'b', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques ['a', 'c'] Categories (3, object): ['a', 'b', 'c'] Notice that 'b' is in uniques.categories, despite not being present in cat.values. For all other pandas objects, an Index of the appropriate type is returned. >>> cat = pd.Series(['a', 'a', 'c']) >>> codes, uniques = pd.factorize(cat) >>> codes array([0, 0, 1]...) >>> uniques Index(['a', 'c'], dtype='object') If NaN is in the values, and we want to include NaN in the uniques of the values, it can be achieved by setting na_sentinel=None. >>> values = np.array([1, 2, 1, np.nan]) >>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1 >>> codes array([ 0, 1, 0, -1]) >>> uniques array([1., 2.]) >>> codes, uniques = pd.factorize(values, na_sentinel=None) >>> codes array([0, 1, 0, 2]) >>> uniques array([ 1., 2., nan])
pandas.reference.api.pandas.index.factorize
pandas.Index.fillna Index.fillna(value=None, downcast=None)[source] Fill NA/NaN values with the specified value. Parameters value:scalar Scalar value to use to fill holes (e.g. 0). This value cannot be a list-likes. downcast:dict, default is None A dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible). Returns Index See also DataFrame.fillna Fill NaN values of a DataFrame. Series.fillna Fill NaN Values of a Series.
pandas.reference.api.pandas.index.fillna
pandas.Index.format Index.format(name=False, formatter=None, na_rep='NaN')[source] Render a string representation of the Index.
pandas.reference.api.pandas.index.format
pandas.Index.get_indexer finalIndex.get_indexer(target, method=None, limit=None, tolerance=None)[source] Compute indexer and mask for new index given the current index. The indexer should be then used as an input to ndarray.take to align the current data to the new index. Parameters target:Index method:{None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional default: exact matches only. pad / ffill: find the PREVIOUS index value if no exact match. backfill / bfill: use NEXT index value if no exact match nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value. limit:int, optional Maximum number of consecutive labels in target to match for inexact matches. tolerance:optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations must satisfy the equation abs(index[indexer] - target) <= tolerance. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type. Returns indexer:np.ndarray[np.intp] Integers from 0 to n - 1 indicating that the index at these positions matches the corresponding target values. Missing values in the target are marked by -1. Notes Returns -1 for unmatched values, for further explanation see the example below. Examples >>> index = pd.Index(['c', 'a', 'b']) >>> index.get_indexer(['a', 'b', 'x']) array([ 1, 2, -1]) Notice that the return value is an array of locations in index and x is marked by -1, as it is not in index.
pandas.reference.api.pandas.index.get_indexer
pandas.Index.get_indexer_for finalIndex.get_indexer_for(target)[source] Guaranteed return of an indexer even when non-unique. This dispatches to get_indexer or get_indexer_non_unique as appropriate. Returns np.ndarray[np.intp] List of indices. Examples >>> idx = pd.Index([np.nan, 'var1', np.nan]) >>> idx.get_indexer_for([np.nan]) array([0, 2])
pandas.reference.api.pandas.index.get_indexer_for
pandas.Index.get_indexer_non_unique Index.get_indexer_non_unique(target)[source] Compute indexer and mask for new index given the current index. The indexer should be then used as an input to ndarray.take to align the current data to the new index. Parameters target:Index Returns indexer:np.ndarray[np.intp] Integers from 0 to n - 1 indicating that the index at these positions matches the corresponding target values. Missing values in the target are marked by -1. missing:np.ndarray[np.intp] An indexer into the target of the values not found. These correspond to the -1 in the indexer array.
pandas.reference.api.pandas.index.get_indexer_non_unique
pandas.Index.get_level_values Index.get_level_values(level)[source] Return an Index of values for requested level. This is primarily useful to get an individual level of values from a MultiIndex, but is provided on Index as well for compatibility. Parameters level:int or str It is either the integer position or the name of the level. Returns Index Calling object, as there is only one level in the Index. See also MultiIndex.get_level_values Get values for a level of a MultiIndex. Notes For Index, level should be 0, since there are no multiple levels. Examples >>> idx = pd.Index(list('abc')) >>> idx Index(['a', 'b', 'c'], dtype='object') Get level values by supplying level as integer: >>> idx.get_level_values(0) Index(['a', 'b', 'c'], dtype='object')
pandas.reference.api.pandas.index.get_level_values
pandas.Index.get_loc Index.get_loc(key, method=None, tolerance=None)[source] Get integer location, slice or boolean mask for requested label. Parameters key:label method:{None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional default: exact matches only. pad / ffill: find the PREVIOUS index value if no exact match. backfill / bfill: use NEXT index value if no exact match nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value. tolerance:int or float, optional Maximum distance from index value for inexact matches. The value of the index at the matching location must satisfy the equation abs(index[loc] - key) <= tolerance. Returns loc:int if unique index, slice if monotonic index, else mask Examples >>> unique_index = pd.Index(list('abc')) >>> unique_index.get_loc('b') 1 >>> monotonic_index = pd.Index(list('abbc')) >>> monotonic_index.get_loc('b') slice(1, 3, None) >>> non_monotonic_index = pd.Index(list('abcb')) >>> non_monotonic_index.get_loc('b') array([False, True, False, True])
pandas.reference.api.pandas.index.get_loc
pandas.Index.get_slice_bound Index.get_slice_bound(label, side, kind=NoDefault.no_default)[source] Calculate slice bound that corresponds to given label. Returns leftmost (one-past-the-rightmost if side=='right') position of given label. Parameters label:object side:{‘left’, ‘right’} kind:{‘loc’, ‘getitem’} or None Deprecated since version 1.4.0. Returns int Index of label.
pandas.reference.api.pandas.index.get_slice_bound
pandas.Index.get_value finalIndex.get_value(series, key)[source] Fast lookup of value from 1-dimensional ndarray. Only use this if you know what you’re doing. Returns scalar or Series
pandas.reference.api.pandas.index.get_value
pandas.Index.groupby finalIndex.groupby(values)[source] Group the index labels by a given array of values. Parameters values:array Values used to determine the groups. Returns dict {group name -> group labels}
pandas.reference.api.pandas.index.groupby
pandas.Index.has_duplicates propertyIndex.has_duplicates Check if the Index has duplicate values. Returns bool Whether or not the Index has duplicate values. Examples >>> idx = pd.Index([1, 5, 7, 7]) >>> idx.has_duplicates True >>> idx = pd.Index([1, 5, 7]) >>> idx.has_duplicates False >>> idx = pd.Index(["Watermelon", "Orange", "Apple", ... "Watermelon"]).astype("category") >>> idx.has_duplicates True >>> idx = pd.Index(["Orange", "Apple", ... "Watermelon"]).astype("category") >>> idx.has_duplicates False
pandas.reference.api.pandas.index.has_duplicates
pandas.Index.hasnans Index.hasnans Return True if there are any NaNs. Enables various performance speedups.
pandas.reference.api.pandas.index.hasnans
pandas.Index.holds_integer finalIndex.holds_integer()[source] Whether the type is an integer type.
pandas.reference.api.pandas.index.holds_integer
pandas.Index.identical finalIndex.identical(other)[source] Similar to equals, but checks that object attributes and types are also equal. Returns bool If two Index objects have equal elements and same type True, otherwise False.
pandas.reference.api.pandas.index.identical
pandas.Index.inferred_type Index.inferred_type Return a string of the type inferred from the values.
pandas.reference.api.pandas.index.inferred_type
pandas.Index.insert Index.insert(loc, item)[source] Make new Index inserting new item at location. Follows Python numpy.insert semantics for negative values. Parameters loc:int item:object Returns new_index:Index
pandas.reference.api.pandas.index.insert
pandas.Index.intersection finalIndex.intersection(other, sort=False)[source] Form the intersection of two Index objects. This returns a new Index with elements common to the index and other. Parameters other:Index or array-like sort:False or None, default False Whether to sort the resulting index. False : do not sort the result. None : sort the result, except when self and other are equal or when the values cannot be compared. Returns intersection:Index Examples >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([3, 4, 5, 6]) >>> idx1.intersection(idx2) Int64Index([3, 4], dtype='int64')
pandas.reference.api.pandas.index.intersection
pandas.Index.is_ finalIndex.is_(other)[source] More flexible, faster check like is but that works through views. Note: this is not the same as Index.identical(), which checks that metadata is also the same. Parameters other:object Other object to compare against. Returns bool True if both have same underlying data, False otherwise. See also Index.identical Works like Index.is_ but also checks metadata.
pandas.reference.api.pandas.index.is_
pandas.Index.is_all_dates Index.is_all_dates Whether or not the index values only consist of dates.
pandas.reference.api.pandas.index.is_all_dates
pandas.Index.is_boolean finalIndex.is_boolean()[source] Check if the Index only consists of booleans. Returns bool Whether or not the Index only consists of booleans. See also is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index([True, False, True]) >>> idx.is_boolean() True >>> idx = pd.Index(["True", "False", "True"]) >>> idx.is_boolean() False >>> idx = pd.Index([True, False, "True"]) >>> idx.is_boolean() False
pandas.reference.api.pandas.index.is_boolean
pandas.Index.is_categorical finalIndex.is_categorical()[source] Check if the Index holds categorical data. Returns bool True if the Index is categorical. See also CategoricalIndex Index for categorical data. is_boolean Check if the Index only consists of booleans. is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index(["Watermelon", "Orange", "Apple", ... "Watermelon"]).astype("category") >>> idx.is_categorical() True >>> idx = pd.Index([1, 3, 5, 7]) >>> idx.is_categorical() False >>> s = pd.Series(["Peter", "Victor", "Elisabeth", "Mar"]) >>> s 0 Peter 1 Victor 2 Elisabeth 3 Mar dtype: object >>> s.index.is_categorical() False
pandas.reference.api.pandas.index.is_categorical
pandas.Index.is_floating finalIndex.is_floating()[source] Check if the Index is a floating type. The Index may consist of only floats, NaNs, or a mix of floats, integers, or NaNs. Returns bool Whether or not the Index only consists of only consists of floats, NaNs, or a mix of floats, integers, or NaNs. See also is_boolean Check if the Index only consists of booleans. is_integer Check if the Index only consists of integers. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) >>> idx.is_floating() True >>> idx = pd.Index([1.0, 2.0, np.nan, 4.0]) >>> idx.is_floating() True >>> idx = pd.Index([1, 2, 3, 4, np.nan]) >>> idx.is_floating() True >>> idx = pd.Index([1, 2, 3, 4]) >>> idx.is_floating() False
pandas.reference.api.pandas.index.is_floating
pandas.Index.is_integer finalIndex.is_integer()[source] Check if the Index only consists of integers. Returns bool Whether or not the Index only consists of integers. See also is_boolean Check if the Index only consists of booleans. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index([1, 2, 3, 4]) >>> idx.is_integer() True >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) >>> idx.is_integer() False >>> idx = pd.Index(["Apple", "Mango", "Watermelon"]) >>> idx.is_integer() False
pandas.reference.api.pandas.index.is_integer
pandas.Index.is_interval finalIndex.is_interval()[source] Check if the Index holds Interval objects. Returns bool Whether or not the Index holds Interval objects. See also IntervalIndex Index for Interval objects. is_boolean Check if the Index only consists of booleans. is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index([pd.Interval(left=0, right=5), ... pd.Interval(left=5, right=10)]) >>> idx.is_interval() True >>> idx = pd.Index([1, 3, 5, 7]) >>> idx.is_interval() False
pandas.reference.api.pandas.index.is_interval
pandas.Index.is_mixed finalIndex.is_mixed()[source] Check if the Index holds data with mixed data types. Returns bool Whether or not the Index holds data with mixed data types. See also is_boolean Check if the Index only consists of booleans. is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. Examples >>> idx = pd.Index(['a', np.nan, 'b']) >>> idx.is_mixed() True >>> idx = pd.Index([1.0, 2.0, 3.0, 5.0]) >>> idx.is_mixed() False
pandas.reference.api.pandas.index.is_mixed
pandas.Index.is_monotonic propertyIndex.is_monotonic Alias for is_monotonic_increasing.
pandas.reference.api.pandas.index.is_monotonic
pandas.Index.is_monotonic_decreasing propertyIndex.is_monotonic_decreasing Return if the index is monotonic decreasing (only equal or decreasing) values. Examples >>> Index([3, 2, 1]).is_monotonic_decreasing True >>> Index([3, 2, 2]).is_monotonic_decreasing True >>> Index([3, 1, 2]).is_monotonic_decreasing False
pandas.reference.api.pandas.index.is_monotonic_decreasing
pandas.Index.is_monotonic_increasing propertyIndex.is_monotonic_increasing Return if the index is monotonic increasing (only equal or increasing) values. Examples >>> Index([1, 2, 3]).is_monotonic_increasing True >>> Index([1, 2, 2]).is_monotonic_increasing True >>> Index([1, 3, 2]).is_monotonic_increasing False
pandas.reference.api.pandas.index.is_monotonic_increasing
pandas.Index.is_numeric finalIndex.is_numeric()[source] Check if the Index only consists of numeric data. Returns bool Whether or not the Index only consists of numeric data. See also is_boolean Check if the Index only consists of booleans. is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_object Check if the Index is of the object dtype. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) >>> idx.is_numeric() True >>> idx = pd.Index([1, 2, 3, 4.0]) >>> idx.is_numeric() True >>> idx = pd.Index([1, 2, 3, 4]) >>> idx.is_numeric() True >>> idx = pd.Index([1, 2, 3, 4.0, np.nan]) >>> idx.is_numeric() True >>> idx = pd.Index([1, 2, 3, 4.0, np.nan, "Apple"]) >>> idx.is_numeric() False
pandas.reference.api.pandas.index.is_numeric
pandas.Index.is_object finalIndex.is_object()[source] Check if the Index is of the object dtype. Returns bool Whether or not the Index is of the object dtype. See also is_boolean Check if the Index only consists of booleans. is_integer Check if the Index only consists of integers. is_floating Check if the Index is a floating type. is_numeric Check if the Index only consists of numeric data. is_categorical Check if the Index holds categorical data. is_interval Check if the Index holds Interval objects. is_mixed Check if the Index holds data with mixed data types. Examples >>> idx = pd.Index(["Apple", "Mango", "Watermelon"]) >>> idx.is_object() True >>> idx = pd.Index(["Apple", "Mango", 2.0]) >>> idx.is_object() True >>> idx = pd.Index(["Watermelon", "Orange", "Apple", ... "Watermelon"]).astype("category") >>> idx.is_object() False >>> idx = pd.Index([1.0, 2.0, 3.0, 4.0]) >>> idx.is_object() False
pandas.reference.api.pandas.index.is_object
pandas.Index.is_type_compatible Index.is_type_compatible(kind)[source] Whether the index type is compatible with the provided type.
pandas.reference.api.pandas.index.is_type_compatible
pandas.Index.is_unique Index.is_unique Return if the index has unique values.
pandas.reference.api.pandas.index.is_unique
pandas.Index.isin Index.isin(values, level=None)[source] Return a boolean array where the index values are in values. Compute boolean array of whether each index value is found in the passed set of values. The length of the returned boolean array matches the length of the index. Parameters values:set or list-like Sought values. level:str or int, optional Name or position of the index level to use (if the index is a MultiIndex). Returns np.ndarray[bool] NumPy array of boolean values. See also Series.isin Same for Series. DataFrame.isin Same method for DataFrames. Notes In the case of MultiIndex you must either specify values as a list-like object containing tuples that are the same length as the number of levels, or specify level. Otherwise it will raise a ValueError. If level is specified: if it is the name of one and only one index level, use that level; otherwise it should be a number indicating level position. Examples >>> idx = pd.Index([1,2,3]) >>> idx Int64Index([1, 2, 3], dtype='int64') Check whether each index value in a list of values. >>> idx.isin([1, 4]) array([ True, False, False]) >>> midx = pd.MultiIndex.from_arrays([[1,2,3], ... ['red', 'blue', 'green']], ... names=('number', 'color')) >>> midx MultiIndex([(1, 'red'), (2, 'blue'), (3, 'green')], names=['number', 'color']) Check whether the strings in the ‘color’ level of the MultiIndex are in a list of colors. >>> midx.isin(['red', 'orange', 'yellow'], level='color') array([ True, False, False]) To check across the levels of a MultiIndex, pass a list of tuples: >>> midx.isin([(1, 'red'), (3, 'red')]) array([ True, False, False]) For a DatetimeIndex, string values in values are converted to Timestamps. >>> dates = ['2000-03-11', '2000-03-12', '2000-03-13'] >>> dti = pd.to_datetime(dates) >>> dti DatetimeIndex(['2000-03-11', '2000-03-12', '2000-03-13'], dtype='datetime64[ns]', freq=None) >>> dti.isin(['2000-03-11']) array([ True, False, False])
pandas.reference.api.pandas.index.isin
pandas.Index.isna finalIndex.isna()[source] Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None, numpy.NaN or pd.NaT, get mapped to True values. Everything else get mapped to False values. Characters such as empty strings ‘’ or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns numpy.ndarray[bool] A boolean array of whether my values are NA. See also Index.notna Boolean inverse of isna. Index.dropna Omit entries with missing values. isna Top-level isna. Series.isna Detect missing values in Series object. Examples Show which entries in a pandas.Index are NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.isna() array([False, False, True]) Empty strings are not considered NA values. None is considered an NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.isna() array([False, False, False, True]) For datetimes, NaT (Not a Time) is considered as an NA value. >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'), ... pd.Timestamp(''), None, pd.NaT]) >>> idx DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'], dtype='datetime64[ns]', freq=None) >>> idx.isna() array([False, True, True, True])
pandas.reference.api.pandas.index.isna
pandas.Index.isnull Index.isnull()[source] Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None, numpy.NaN or pd.NaT, get mapped to True values. Everything else get mapped to False values. Characters such as empty strings ‘’ or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns numpy.ndarray[bool] A boolean array of whether my values are NA. See also Index.notna Boolean inverse of isna. Index.dropna Omit entries with missing values. isna Top-level isna. Series.isna Detect missing values in Series object. Examples Show which entries in a pandas.Index are NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.isna() array([False, False, True]) Empty strings are not considered NA values. None is considered an NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.isna() array([False, False, False, True]) For datetimes, NaT (Not a Time) is considered as an NA value. >>> idx = pd.DatetimeIndex([pd.Timestamp('1940-04-25'), ... pd.Timestamp(''), None, pd.NaT]) >>> idx DatetimeIndex(['1940-04-25', 'NaT', 'NaT', 'NaT'], dtype='datetime64[ns]', freq=None) >>> idx.isna() array([False, True, True, True])
pandas.reference.api.pandas.index.isnull
pandas.Index.item Index.item()[source] Return the first element of the underlying data as a Python scalar. Returns scalar The first element of %(klass)s. Raises ValueError If the data is not length-1.
pandas.reference.api.pandas.index.item
pandas.Index.join finalIndex.join(other, how='left', level=None, return_indexers=False, sort=False)[source] Compute join_index and indexers to conform data structures to the new index. Parameters other:Index how:{‘left’, ‘right’, ‘inner’, ‘outer’} level:int or level name, default None return_indexers:bool, default False sort:bool, default False Sort the join keys lexicographically in the result Index. If False, the order of the join keys depends on the join type (how keyword). Returns join_index, (left_indexer, right_indexer)
pandas.reference.api.pandas.index.join
pandas.Index.map Index.map(mapper, na_action=None)[source] Map values using an input mapping or function. Parameters mapper:function, dict, or Series Mapping correspondence. na_action:{None, ‘ignore’} If ‘ignore’, propagate NA values, without passing them to the mapping correspondence. Returns applied:Union[Index, MultiIndex], inferred The output of the mapping function applied to the index. If the function returns a tuple with more than one element a MultiIndex will be returned.
pandas.reference.api.pandas.index.map
pandas.Index.max Index.max(axis=None, skipna=True, *args, **kwargs)[source] Return the maximum value of the Index. Parameters axis:int, optional For compatibility with NumPy. Only 0 or None are allowed. skipna:bool, default True Exclude NA/null values when showing the result. *args, **kwargs Additional arguments and keywords for compatibility with NumPy. Returns scalar Maximum value. See also Index.min Return the minimum value in an Index. Series.max Return the maximum value in a Series. DataFrame.max Return the maximum values in a DataFrame. Examples >>> idx = pd.Index([3, 2, 1]) >>> idx.max() 3 >>> idx = pd.Index(['c', 'b', 'a']) >>> idx.max() 'c' For a MultiIndex, the maximum is determined lexicographically. >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)]) >>> idx.max() ('b', 2)
pandas.reference.api.pandas.index.max
pandas.Index.memory_usage Index.memory_usage(deep=False)[source] Memory usage of the values. Parameters deep:bool, default False Introspect the data deeply, interrogate object dtypes for system-level memory consumption. Returns bytes used See also numpy.ndarray.nbytes Total bytes consumed by the elements of the array. Notes Memory usage does not include memory consumed by elements that are not components of the array if deep=False or if used on PyPy
pandas.reference.api.pandas.index.memory_usage
pandas.Index.min Index.min(axis=None, skipna=True, *args, **kwargs)[source] Return the minimum value of the Index. Parameters axis:{None} Dummy argument for consistency with Series. skipna:bool, default True Exclude NA/null values when showing the result. *args, **kwargs Additional arguments and keywords for compatibility with NumPy. Returns scalar Minimum value. See also Index.max Return the maximum value of the object. Series.min Return the minimum value in a Series. DataFrame.min Return the minimum values in a DataFrame. Examples >>> idx = pd.Index([3, 2, 1]) >>> idx.min() 1 >>> idx = pd.Index(['c', 'b', 'a']) >>> idx.min() 'a' For a MultiIndex, the minimum is determined lexicographically. >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)]) >>> idx.min() ('a', 1)
pandas.reference.api.pandas.index.min
pandas.Index.name propertyIndex.name Return Index or MultiIndex name.
pandas.reference.api.pandas.index.name
pandas.Index.names propertyIndex.names
pandas.reference.api.pandas.index.names
pandas.Index.nbytes propertyIndex.nbytes Return the number of bytes in the underlying data.
pandas.reference.api.pandas.index.nbytes
pandas.Index.ndim propertyIndex.ndim Number of dimensions of the underlying data, by definition 1.
pandas.reference.api.pandas.index.ndim
pandas.Index.nlevels propertyIndex.nlevels Number of levels.
pandas.reference.api.pandas.index.nlevels
pandas.Index.notna finalIndex.notna()[source] Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values. Returns numpy.ndarray[bool] Boolean array to indicate which entries are not NA. See also Index.notnull Alias of notna. Index.isna Inverse of notna. notna Top-level notna. Examples Show which entries in an Index are not NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.notna() array([ True, True, False]) Empty strings are not considered NA values. None is considered a NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.notna() array([ True, True, True, False])
pandas.reference.api.pandas.index.notna
pandas.Index.notnull Index.notnull()[source] Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to True. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). NA values, such as None or numpy.NaN, get mapped to False values. Returns numpy.ndarray[bool] Boolean array to indicate which entries are not NA. See also Index.notnull Alias of notna. Index.isna Inverse of notna. notna Top-level notna. Examples Show which entries in an Index are not NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.notna() array([ True, True, False]) Empty strings are not considered NA values. None is considered a NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.notna() array([ True, True, True, False])
pandas.reference.api.pandas.index.notnull
pandas.Index.nunique Index.nunique(dropna=True)[source] Return number of unique elements in the object. Excludes NA values by default. Parameters dropna:bool, default True Don’t include NaN in the count. Returns int See also DataFrame.nunique Method nunique for DataFrame. Series.count Count non-NA/null observations in the Series. Examples >>> s = pd.Series([1, 3, 5, 7, 7]) >>> s 0 1 1 3 2 5 3 7 4 7 dtype: int64 >>> s.nunique() 4
pandas.reference.api.pandas.index.nunique
pandas.Index.putmask finalIndex.putmask(mask, value)[source] Return a new Index of the values set with the mask. Returns Index See also numpy.ndarray.putmask Changes elements of an array based on conditional and input values.
pandas.reference.api.pandas.index.putmask
pandas.Index.ravel finalIndex.ravel(order='C')[source] Return an ndarray of the flattened values of the underlying data. Returns numpy.ndarray Flattened array. See also numpy.ndarray.ravel Return a flattened array.
pandas.reference.api.pandas.index.ravel
pandas.Index.reindex Index.reindex(target, method=None, level=None, limit=None, tolerance=None)[source] Create index with target’s values. Parameters target:an iterable method:{None, ‘pad’/’ffill’, ‘backfill’/’bfill’, ‘nearest’}, optional default: exact matches only. pad / ffill: find the PREVIOUS index value if no exact match. backfill / bfill: use NEXT index value if no exact match nearest: use the NEAREST index value if no exact match. Tied distances are broken by preferring the larger index value. level:int, optional Level of multiindex. limit:int, optional Maximum number of consecutive labels in target to match for inexact matches. tolerance:int or float, optional Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations must satisfy the equation abs(index[indexer] - target) <= tolerance. Tolerance may be a scalar value, which applies the same tolerance to all values, or list-like, which applies variable tolerance per element. List-like includes list, tuple, array, Series, and must be the same size as the index and its dtype must exactly match the index’s type. Returns new_index:pd.Index Resulting index. indexer:np.ndarray[np.intp] or None Indices of output values in original index. Raises TypeError If method passed along with level. ValueError If non-unique multi-index ValueError If non-unique index and method or limit passed. See also Series.reindex DataFrame.reindex Examples >>> idx = pd.Index(['car', 'bike', 'train', 'tractor']) >>> idx Index(['car', 'bike', 'train', 'tractor'], dtype='object') >>> idx.reindex(['car', 'bike']) (Index(['car', 'bike'], dtype='object'), array([0, 1]))
pandas.reference.api.pandas.index.reindex
pandas.Index.rename Index.rename(name, inplace=False)[source] Alter Index or MultiIndex name. Able to set new names without level. Defaults to returning new index. Length of names must match number of levels in MultiIndex. Parameters name:label or list of labels Name(s) to set. inplace:bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns Index or None The same type as the caller or None if inplace=True. See also Index.set_names Able to set new names partially and by level. Examples >>> idx = pd.Index(['A', 'C', 'A', 'B'], name='score') >>> idx.rename('grade') Index(['A', 'C', 'A', 'B'], dtype='object', name='grade') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]], ... names=['kind', 'year']) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['kind', 'year']) >>> idx.rename(['species', 'year']) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['species', 'year']) >>> idx.rename('species') Traceback (most recent call last): TypeError: Must pass list-like as `names`.
pandas.reference.api.pandas.index.rename
pandas.Index.repeat Index.repeat(repeats, axis=None)[source] Repeat elements of a Index. Returns a new Index where each element of the current Index is repeated consecutively a given number of times. Parameters repeats:int or array of ints The number of repetitions for each element. This should be a non-negative integer. Repeating 0 times will return an empty Index. axis:None Must be None. Has no effect but is accepted for compatibility with numpy. Returns repeated_index:Index Newly created Index with repeated elements. See also Series.repeat Equivalent function for Series. numpy.repeat Similar method for numpy.ndarray. Examples >>> idx = pd.Index(['a', 'b', 'c']) >>> idx Index(['a', 'b', 'c'], dtype='object') >>> idx.repeat(2) Index(['a', 'a', 'b', 'b', 'c', 'c'], dtype='object') >>> idx.repeat([1, 2, 3]) Index(['a', 'b', 'b', 'c', 'c', 'c'], dtype='object')
pandas.reference.api.pandas.index.repeat
pandas.Index.searchsorted Index.searchsorted(value, side='left', sorter=None)[source] Find indices where elements should be inserted to maintain order. Find the indices into a sorted Index self such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved. Note The Index must be monotonically sorted, otherwise wrong locations will likely be returned. Pandas does not check this for you. Parameters value:array-like or scalar Values to insert into self. side:{‘left’, ‘right’}, optional If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self). sorter:1-D array-like, optional Optional array of integer indices that sort self into ascending order. They are typically the result of np.argsort. Returns int or array of int A scalar or array of insertion points with the same shape as value. See also sort_values Sort by the values along either axis. numpy.searchsorted Similar method from NumPy. Notes Binary search is used to find the required insertion points. Examples >>> ser = pd.Series([1, 2, 3]) >>> ser 0 1 1 2 2 3 dtype: int64 >>> ser.searchsorted(4) 3 >>> ser.searchsorted([0, 4]) array([0, 3]) >>> ser.searchsorted([1, 3], side='left') array([0, 2]) >>> ser.searchsorted([1, 3], side='right') array([1, 3]) >>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000'])) >>> ser 0 2000-03-11 1 2000-03-12 2 2000-03-13 dtype: datetime64[ns] >>> ser.searchsorted('3/14/2000') 3 >>> ser = pd.Categorical( ... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True ... ) >>> ser ['apple', 'bread', 'bread', 'cheese', 'milk'] Categories (4, object): ['apple' < 'bread' < 'cheese' < 'milk'] >>> ser.searchsorted('bread') 1 >>> ser.searchsorted(['bread'], side='right') array([3]) If the values are not monotonically sorted, wrong locations may be returned: >>> ser = pd.Series([2, 1, 3]) >>> ser 0 2 1 1 2 3 dtype: int64 >>> ser.searchsorted(1) 0 # wrong result, correct would be 1
pandas.reference.api.pandas.index.searchsorted
pandas.Index.set_names Index.set_names(names, level=None, inplace=False)[source] Set Index or MultiIndex name. Able to set new names partially and by level. Parameters names:label or list of label or dict-like for MultiIndex Name(s) to set. Changed in version 1.3.0. level:int, label or list of int or label, optional If the index is a MultiIndex and names is not dict-like, level(s) to set (None for all levels). Otherwise level must be None. Changed in version 1.3.0. inplace:bool, default False Modifies the object directly, instead of creating a new Index or MultiIndex. Returns Index or None The same type as the caller or None if inplace=True. See also Index.rename Able to set new names without level. Examples >>> idx = pd.Index([1, 2, 3, 4]) >>> idx Int64Index([1, 2, 3, 4], dtype='int64') >>> idx.set_names('quarter') Int64Index([1, 2, 3, 4], dtype='int64', name='quarter') >>> idx = pd.MultiIndex.from_product([['python', 'cobra'], ... [2018, 2019]]) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], ) >>> idx.set_names(['kind', 'year'], inplace=True) >>> idx MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['kind', 'year']) >>> idx.set_names('species', level=0) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['species', 'year']) When renaming levels with a dict, levels can not be passed. >>> idx.set_names({'kind': 'snake'}) MultiIndex([('python', 2018), ('python', 2019), ( 'cobra', 2018), ( 'cobra', 2019)], names=['snake', 'year'])
pandas.reference.api.pandas.index.set_names
pandas.Index.set_value finalIndex.set_value(arr, key, value)[source] Fast lookup of value from 1-dimensional ndarray. Deprecated since version 1.0. Notes Only use this if you know what you’re doing.
pandas.reference.api.pandas.index.set_value
pandas.Index.shape propertyIndex.shape Return a tuple of the shape of the underlying data.
pandas.reference.api.pandas.index.shape
pandas.Index.shift Index.shift(periods=1, freq=None)[source] Shift index by desired number of time frequency increments. This method is for shifting the values of datetime-like indexes by a specified time increment a given number of times. Parameters periods:int, default 1 Number of periods (or increments) to shift by, can be positive or negative. freq:pandas.DateOffset, pandas.Timedelta or str, optional Frequency increment to shift by. If None, the index is shifted by its own freq attribute. Offset aliases are valid strings, e.g., ‘D’, ‘W’, ‘M’ etc. Returns pandas.Index Shifted index. See also Series.shift Shift values of Series. Notes This method is only implemented for datetime-like index classes, i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex. Examples Put the first 5 month starts of 2011 into an index. >>> month_starts = pd.date_range('1/1/2011', periods=5, freq='MS') >>> month_starts DatetimeIndex(['2011-01-01', '2011-02-01', '2011-03-01', '2011-04-01', '2011-05-01'], dtype='datetime64[ns]', freq='MS') Shift the index by 10 days. >>> month_starts.shift(10, freq='D') DatetimeIndex(['2011-01-11', '2011-02-11', '2011-03-11', '2011-04-11', '2011-05-11'], dtype='datetime64[ns]', freq=None) The default value of freq is the freq attribute of the index, which is ‘MS’ (month start) in this example. >>> month_starts.shift(10) DatetimeIndex(['2011-11-01', '2011-12-01', '2012-01-01', '2012-02-01', '2012-03-01'], dtype='datetime64[ns]', freq='MS')
pandas.reference.api.pandas.index.shift
pandas.Index.size propertyIndex.size Return the number of elements in the underlying data.
pandas.reference.api.pandas.index.size
pandas.Index.slice_indexer Index.slice_indexer(start=None, end=None, step=None, kind=NoDefault.no_default)[source] Compute the slice indexer for input labels and step. Index needs to be ordered and unique. Parameters start:label, default None If None, defaults to the beginning. end:label, default None If None, defaults to the end. step:int, default None kind:str, default None Deprecated since version 1.4.0. Returns indexer:slice Raises KeyError:If key does not exist, or key is not unique and index is not ordered. Notes This function assumes that the data is sorted, so use at your own peril Examples This is a method on all index types. For example you can do: >>> idx = pd.Index(list('abcd')) >>> idx.slice_indexer(start='b', end='c') slice(1, 3, None) >>> idx = pd.MultiIndex.from_arrays([list('abcd'), list('efgh')]) >>> idx.slice_indexer(start='b', end=('c', 'g')) slice(1, 3, None)
pandas.reference.api.pandas.index.slice_indexer
pandas.Index.slice_locs Index.slice_locs(start=None, end=None, step=None, kind=NoDefault.no_default)[source] Compute slice locations for input labels. Parameters start:label, default None If None, defaults to the beginning. end:label, default None If None, defaults to the end. step:int, defaults None If None, defaults to 1. kind:{‘loc’, ‘getitem’} or None Deprecated since version 1.4.0. Returns start, end:int See also Index.get_loc Get location for a single label. Notes This method only works if the index is monotonic or unique. Examples >>> idx = pd.Index(list('abcd')) >>> idx.slice_locs(start='b', end='c') (1, 3)
pandas.reference.api.pandas.index.slice_locs
pandas.Index.sort finalIndex.sort(*args, **kwargs)[source] Use sort_values instead.
pandas.reference.api.pandas.index.sort
pandas.Index.sort_values Index.sort_values(return_indexer=False, ascending=True, na_position='last', key=None)[source] Return a sorted copy of the index. Return a sorted copy of the index, and optionally return the indices that sorted the index itself. Parameters return_indexer:bool, default False Should the indices that would sort the index be returned. ascending:bool, default True Should the index values be sorted in an ascending order. na_position:{‘first’ or ‘last’}, default ‘last’ Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end. New in version 1.2.0. key:callable, optional If not None, apply the key function to the index values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect an Index and return an Index of the same shape. New in version 1.1.0. Returns sorted_index:pandas.Index Sorted copy of the index. indexer:numpy.ndarray, optional The indices that the index itself was sorted by. See also Series.sort_values Sort values of a Series. DataFrame.sort_values Sort values in a DataFrame. Examples >>> idx = pd.Index([10, 100, 1, 1000]) >>> idx Int64Index([10, 100, 1, 1000], dtype='int64') Sort values in ascending order (default behavior). >>> idx.sort_values() Int64Index([1, 10, 100, 1000], dtype='int64') Sort values in descending order, and also get the indices idx was sorted by. >>> idx.sort_values(ascending=False, return_indexer=True) (Int64Index([1000, 100, 10, 1], dtype='int64'), array([3, 1, 0, 2]))
pandas.reference.api.pandas.index.sort_values
pandas.Index.sortlevel Index.sortlevel(level=None, ascending=True, sort_remaining=None)[source] For internal compatibility with the Index API. Sort the Index. This is for compat with MultiIndex Parameters ascending:bool, default True False to sort in descending order level, sort_remaining are compat parameters Returns Index
pandas.reference.api.pandas.index.sortlevel
pandas.Index.str Index.str()[source] Vectorized string functions for Series and Index. NAs stay NA unless handled otherwise by a particular method. Patterned after Python’s string methods, with some inspiration from R’s stringr package. Examples >>> s = pd.Series(["A_Str_Series"]) >>> s 0 A_Str_Series dtype: object >>> s.str.split("_") 0 [A, Str, Series] dtype: object >>> s.str.replace("_", "") 0 AStrSeries dtype: object
pandas.reference.api.pandas.index.str
pandas.Index.symmetric_difference Index.symmetric_difference(other, result_name=None, sort=None)[source] Compute the symmetric difference of two Index objects. Parameters other:Index or array-like result_name:str sort:False or None, default None Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. False : Do not sort the result. Returns symmetric_difference:Index Notes symmetric_difference contains elements that appear in either idx1 or idx2 but not both. Equivalent to the Index created by idx1.difference(idx2) | idx2.difference(idx1) with duplicates dropped. Examples >>> idx1 = pd.Index([1, 2, 3, 4]) >>> idx2 = pd.Index([2, 3, 4, 5]) >>> idx1.symmetric_difference(idx2) Int64Index([1, 5], dtype='int64')
pandas.reference.api.pandas.index.symmetric_difference
pandas.Index.T propertyIndex.T Return the transpose, which is by definition self.
pandas.reference.api.pandas.index.t
pandas.Index.take Index.take(indices, axis=0, allow_fill=True, fill_value=None, **kwargs)[source] Return a new Index of the values selected by the indices. For internal compatibility with numpy arrays. Parameters indices:array-like Indices to be taken. axis:int, optional The axis over which to select values, always 0. allow_fill:bool, default True fill_value:scalar, default None If allow_fill=True and fill_value is not None, indices specified by -1 are regarded as NA. If Index doesn’t hold NA, raise ValueError. Returns Index An index formed of elements at the given indices. Will be the same type as self, except for RangeIndex. See also numpy.ndarray.take Return an array formed from the elements of a at the given indices.
pandas.reference.api.pandas.index.take
pandas.Index.to_flat_index Index.to_flat_index()[source] Identity method. This is implemented for compatibility with subclass implementations when chaining. Returns pd.Index Caller. See also MultiIndex.to_flat_index Subclass implementation.
pandas.reference.api.pandas.index.to_flat_index
pandas.Index.to_frame Index.to_frame(index=True, name=NoDefault.no_default)[source] Create a DataFrame with a column containing the Index. Parameters index:bool, default True Set the index of the returned DataFrame as the original Index. name:object, default None The passed name should substitute for the index name (if it has one). Returns DataFrame DataFrame containing the original Index data. See also Index.to_series Convert an Index to a Series. Series.to_frame Convert Series to DataFrame. Examples >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') >>> idx.to_frame() animal animal Ant Ant Bear Bear Cow Cow By default, the original Index is reused. To enforce a new Index: >>> idx.to_frame(index=False) animal 0 Ant 1 Bear 2 Cow To override the name of the resulting column, specify name: >>> idx.to_frame(index=False, name='zoo') zoo 0 Ant 1 Bear 2 Cow
pandas.reference.api.pandas.index.to_frame
pandas.Index.to_list Index.to_list()[source] Return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) Returns list See also numpy.ndarray.tolist Return the array as an a.ndim-levels deep nested list of Python scalars.
pandas.reference.api.pandas.index.to_list
pandas.Index.to_native_types finalIndex.to_native_types(slicer=None, **kwargs)[source] Format specified values of self and return them. Deprecated since version 1.2.0. Parameters slicer:int, array-like An indexer into self that specifies which values are used in the formatting process. kwargs:dict Options for specifying how the values should be formatted. These options include the following: na_rep:str The value that serves as a placeholder for NULL values quoting:bool or None Whether or not there are quoted values in self date_format:str The format used to represent date-like values. Returns numpy.ndarray Formatted values.
pandas.reference.api.pandas.index.to_native_types
pandas.Index.to_numpy Index.to_numpy(dtype=None, copy=False, na_value=NoDefault.no_default, **kwargs)[source] A NumPy ndarray representing the values in this Series or Index. Parameters dtype:str or numpy.dtype, optional The dtype to pass to numpy.asarray(). copy:bool, default False Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary. na_value:Any, optional The value to use for missing values. The default value depends on dtype and the type of the array. New in version 1.0.0. **kwargs Additional keywords passed through to the to_numpy method of the underlying array (for extension arrays). New in version 1.0.0. Returns numpy.ndarray See also Series.array Get the actual data stored within. Index.array Get the actual data stored within. DataFrame.to_numpy Similar method for DataFrame. Notes The returned array will be the same up to equality (values equal in self will be equal in the returned array; likewise for values that are not equal). When self contains an ExtensionArray, the dtype may be different. For example, for a category-dtype Series, to_numpy() will return a NumPy array and the categorical dtype will be lost. For NumPy dtypes, this will be a reference to the actual data stored in this Series or Index (assuming copy=False). Modifying the result in place will modify the data stored in the Series or Index (not that we recommend doing that). For extension types, to_numpy() may require copying data and coercing the result to a NumPy type (possibly object), which may be expensive. When you need a no-copy reference to the underlying data, Series.array should be used instead. This table lays out the different dtypes and default return types of to_numpy() for various dtypes within pandas. dtype array type category[T] ndarray[T] (same dtype as input) period ndarray[object] (Periods) interval ndarray[object] (Intervals) IntegerNA ndarray[object] datetime64[ns] datetime64[ns] datetime64[ns, tz] ndarray[object] (Timestamps) Examples >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) >>> ser.to_numpy() array(['a', 'b', 'a'], dtype=object) Specify the dtype to control how datetime-aware data is represented. Use dtype=object to return an ndarray of pandas Timestamp objects, each with the correct tz. >>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) >>> ser.to_numpy(dtype=object) array([Timestamp('2000-01-01 00:00:00+0100', tz='CET'), Timestamp('2000-01-02 00:00:00+0100', tz='CET')], dtype=object) Or dtype='datetime64[ns]' to return an ndarray of native datetime64 values. The values are converted to UTC and the timezone info is dropped. >>> ser.to_numpy(dtype="datetime64[ns]") ... array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'], dtype='datetime64[ns]')
pandas.reference.api.pandas.index.to_numpy
pandas.Index.to_series Index.to_series(index=None, name=None)[source] Create a Series with both index and values equal to the index keys. Useful with map for returning an indexer based on an index. Parameters index:Index, optional Index of resulting Series. If None, defaults to original index. name:str, optional Name of resulting Series. If None, defaults to name of original index. Returns Series The dtype will be based on the type of the Index values. See also Index.to_frame Convert an Index to a DataFrame. Series.to_frame Convert Series to DataFrame. Examples >>> idx = pd.Index(['Ant', 'Bear', 'Cow'], name='animal') By default, the original Index and original name is reused. >>> idx.to_series() animal Ant Ant Bear Bear Cow Cow Name: animal, dtype: object To enforce a new Index, specify new labels to index: >>> idx.to_series(index=[0, 1, 2]) 0 Ant 1 Bear 2 Cow Name: animal, dtype: object To override the name of the resulting column, specify name: >>> idx.to_series(name='zoo') animal Ant Ant Bear Bear Cow Cow Name: zoo, dtype: object
pandas.reference.api.pandas.index.to_series
pandas.Index.tolist Index.tolist()[source] Return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) Returns list See also numpy.ndarray.tolist Return the array as an a.ndim-levels deep nested list of Python scalars.
pandas.reference.api.pandas.index.tolist
pandas.Index.transpose Index.transpose(*args, **kwargs)[source] Return the transpose, which is by definition self. Returns %(klass)s
pandas.reference.api.pandas.index.transpose
pandas.Index.union finalIndex.union(other, sort=None)[source] Form the union of two Index objects. If the Index objects are incompatible, both Index objects will be cast to dtype(‘object’) first. Changed in version 0.25.0. Parameters other:Index or array-like sort:bool or None, default None Whether to sort the resulting Index. None : Sort the result, except when self and other are equal. self or other has length 0. Some values in self or other cannot be compared. A RuntimeWarning is issued in this case. False : do not sort the result. Returns union:Index Examples Union matching dtypes >>> 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') Union mismatched dtypes >>> 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 case >>> 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.reference.api.pandas.index.union
pandas.Index.unique Index.unique(level=None)[source] Return unique values in the index. Unique values are returned in order of appearance, this does NOT sort. Parameters level:int or hashable, optional Only return values from specified level (for MultiIndex). If int, gets the level by integer position, else by level name. Returns Index See also unique Numpy array of unique values in that column. Series.unique Return unique values of Series object.
pandas.reference.api.pandas.index.unique