text
stringlengths
81
112k
Change the dtype of a SparseArray. The output will always be a SparseArray. To convert to a dense ndarray with a certain dtype, use :meth:`numpy.asarray`. Parameters ---------- dtype : np.dtype or ExtensionDtype For SparseDtype, this changes the dtype of ...
Map categories using input correspondence (dict, Series, or function). Parameters ---------- mapper : dict, Series, callable The correspondence from old values to new. Returns ------- SparseArray The output array will have the same density as the...
Tests whether all elements evaluate True Returns ------- all : bool See Also -------- numpy.all def all(self, axis=None, *args, **kwargs): """ Tests whether all elements evaluate True Returns ------- all : bool See Also...
Tests whether at least one of elements evaluate True Returns ------- any : bool See Also -------- numpy.any def any(self, axis=0, *args, **kwargs): """ Tests whether at least one of elements evaluate True Returns ------- any : b...
Sum of non-NA/null values Returns ------- sum : float def sum(self, axis=0, *args, **kwargs): """ Sum of non-NA/null values Returns ------- sum : float """ nv.validate_sum(args, kwargs) valid_vals = self._valid_sp_values ...
Cumulative sum of non-NA/null values. When performing the cumulative summation, any non-NA/null values will be skipped. The resulting SparseArray will preserve the locations of NaN values, but the fill value will be `np.nan` regardless. Parameters ---------- axis : int ...
Mean of non-NA/null values Returns ------- mean : float def mean(self, axis=0, *args, **kwargs): """ Mean of non-NA/null values Returns ------- mean : float """ nv.validate_mean(args, kwargs) valid_vals = self._valid_sp_values ...
Tokenize a Python source code string. Parameters ---------- source : str A Python source code string def tokenize_string(source): """Tokenize a Python source code string. Parameters ---------- source : str A Python source code string """ line_reader = StringIO(sour...
Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise precedence is changed to boolean precedence. Parameters ---------- tok : tuple of int, str ints correspond to the all caps constants in the tokenize module Returns ------- t : tuple of int, str Either the inpu...
Replace local variables with a syntactically valid name. Parameters ---------- tok : tuple of int, str ints correspond to the all caps constants in the tokenize module Returns ------- t : tuple of int, str Either the input or token or the replacement values Notes -----...
Clean up a column name if surrounded by backticks. Backtick quoted string are indicated by a certain tokval value. If a string is a backtick quoted token it will processed by :func:`_remove_spaces_column_name` so that the parser can find this string when the query is executed. See also :meth:`NDFra...
Compose a collection of tokenization functions Parameters ---------- source : str A Python source code string f : callable This takes a tuple of (toknum, tokval) as its argument and returns a tuple with the same structure but possibly different elements. Defaults to the ...
Filter out AST nodes that are subclasses of ``superclass``. def _filter_nodes(superclass, all_nodes=_all_nodes): """Filter out AST nodes that are subclasses of ``superclass``.""" node_names = (node.__name__ for node in all_nodes if issubclass(node, superclass)) return frozenset(node_names...
Return a function that raises a NotImplementedError with a passed node name. def _node_not_implemented(node_name, cls): """Return a function that raises a NotImplementedError with a passed node name. """ def f(self, *args, **kwargs): raise NotImplementedError("{name!r} nodes are not " ...
Decorator to disallow certain nodes from parsing. Raises a NotImplementedError instead. Returns ------- disallowed : callable def disallow(nodes): """Decorator to disallow certain nodes from parsing. Raises a NotImplementedError instead. Returns ------- disallowed : callable "...
Return a function to create an op class with its symbol already passed. Returns ------- f : callable def _op_maker(op_class, op_symbol): """Return a function to create an op class with its symbol already passed. Returns ------- f : callable """ def f(self, node, *args, **kwargs):...
Decorator to add default implementation of ops. def add_ops(op_classes): """Decorator to add default implementation of ops.""" def f(cls): for op_attr_name, op_class in op_classes.items(): ops = getattr(cls, '{name}_ops'.format(name=op_attr_name)) ops_map = getattr(cls, '{name}_...
Get the names in an expression def names(self): """Get the names in an expression""" if is_term(self.terms): return frozenset([self.terms.name]) return frozenset(term.name for term in com.flatten(self.terms))
return a boolean whether I can attempt conversion to a TimedeltaIndex def _is_convertible_to_index(other): """ return a boolean whether I can attempt conversion to a TimedeltaIndex """ if isinstance(other, TimedeltaIndex): return True elif (len(other) > 0 and other.inferred_type n...
Return a fixed frequency TimedeltaIndex, with day as the default frequency Parameters ---------- start : string or timedelta-like, default None Left bound for generating timedeltas end : string or timedelta-like, default None Right bound for generating timedeltas periods : integ...
Returns a FrozenList with other concatenated to the end of self. Parameters ---------- other : array-like The array-like whose elements we are concatenating. Returns ------- diff : FrozenList The collection difference between self and other. def...
Returns a FrozenList with elements from other removed from self. Parameters ---------- other : array-like The array-like whose elements we are removing self. Returns ------- diff : FrozenList The collection difference between self and other. def...
Find indices to insert `value` so as to maintain order. For full documentation, see `numpy.searchsorted` See Also -------- numpy.searchsorted : Equivalent function. def searchsorted(self, value, side="left", sorter=None): """ Find indices to insert `value` so as to mai...
Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases. def arrays_to_mgr(arrays, arr_names, index, columns, dtype=None): """ Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases. """ # figure out the ...
Extract from a masked rec array and create the manager. def masked_rec_array_to_mgr(data, index, columns, dtype, copy): """ Extract from a masked rec array and create the manager. """ # essentially process a record array then fill it fill_value = data.fill_value fdata = ma.getdata(data) if...
Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases. def init_dict(data, index, columns, dtype=None): """ Segregate Series based on type and coerce into matrices. Needs to handle a lot of exceptional cases. """ if columns is not None: from...
Return list of arrays, columns. def to_arrays(data, columns, coerce_float=False, dtype=None): """ Return list of arrays, columns. """ if isinstance(data, ABCDataFrame): if columns is not None: arrays = [data._ixs(i, axis=1).values for i, col in enumerate(data.c...
Sanitize an index type to return an ndarray of the underlying, pass through a non-Index. def sanitize_index(data, index, copy=False): """ Sanitize an index type to return an ndarray of the underlying, pass through a non-Index. """ if index is None: return data if len(data) != len(...
Sanitize input data to an ndarray, copy if specified, coerce to the dtype if specified. def sanitize_array(data, index, dtype=None, copy=False, raise_cast_failure=False): """ Sanitize input data to an ndarray, copy if specified, coerce to the dtype if specified. """ if dtype ...
Make sure a valid engine is passed. Parameters ---------- engine : str Raises ------ KeyError * If an invalid engine is passed ImportError * If numexpr was requested but doesn't exist Returns ------- string engine def _check_engine(engine): """Make sure a vali...
Make sure a valid parser is passed. Parameters ---------- parser : str Raises ------ KeyError * If an invalid parser is passed def _check_parser(parser): """Make sure a valid parser is passed. Parameters ---------- parser : str Raises ------ KeyError ...
Evaluate a Python expression as a string using various backends. The following arithmetic operations are supported: ``+``, ``-``, ``*``, ``/``, ``**``, ``%``, ``//`` (python engine only) along with the following boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not). Additionally, the ``'pandas'`...
Transform combination(s) of uint64 in one uint64 (each), in a strictly monotonic way (i.e. respecting the lexicographic order of integer combinations): see BaseMultiIndexCodesEngine documentation. Parameters ---------- codes : 1- or 2-dimensional array of dtype uint64 ...
Convert arrays to MultiIndex. Parameters ---------- arrays : list / sequence of array-likes Each array-like gives one level's value for each data point. len(arrays) is the number of levels. sortorder : int or None Level of sortedness (must be lexicogr...
Convert list of tuples to MultiIndex. Parameters ---------- tuples : list / sequence of tuple-likes Each tuple is the index of one row/column. sortorder : int or None Level of sortedness (must be lexicographically sorted by that level). names ...
Make a MultiIndex from the cartesian product of multiple iterables. Parameters ---------- iterables : list / sequence of iterables Each iterable has unique labels for each level of the index. sortorder : int or None Level of sortedness (must be lexicographically ...
Make a MultiIndex from a DataFrame. .. versionadded:: 0.24.0 Parameters ---------- df : DataFrame DataFrame to be converted to MultiIndex. sortorder : int, optional Level of sortedness (must be lexicographically sorted by that level). ...
Set new levels on MultiIndex. Defaults to returning new index. Parameters ---------- levels : sequence or list of sequence new level(s) to apply level : int, level name, or sequence of int/level names (default None) level(s) to set (None for all levels) ...
Set new codes on MultiIndex. Defaults to returning new index. .. versionadded:: 0.24.0 New name for deprecated method `set_labels`. Parameters ---------- codes : sequence or list of sequence new codes to apply level : int, level name, or sequence...
Make a copy of this object. Names, dtype, levels and codes can be passed and will be set on new copy. Parameters ---------- names : sequence, optional dtype : numpy dtype or pandas type, optional levels : sequence, optional codes : sequence, optional Ret...
this is defined as a copy with the same identity def view(self, cls=None): """ this is defined as a copy with the same identity """ result = self.copy() result._id = self._id return result
return a boolean if we need a qualified .info display def _is_memory_usage_qualified(self): """ return a boolean if we need a qualified .info display """ def f(l): return 'mixed' in l or 'string' in l or 'unicode' in l return any(f(l) for l in self._inferred_type_levels)
return the number of bytes in the underlying data deeply introspect the level data if deep=True include the engine hashtable *this is in internal routine* def _nbytes(self, deep=False): """ return the number of bytes in the underlying data deeply introspect the level d...
Return a list of tuples of the (attr,formatted_value) def _format_attrs(self): """ Return a list of tuples of the (attr,formatted_value) """ attrs = [ ('levels', ibase.default_pprint(self._levels, max_seq_items=False)), ...
Set new names on index. Each name has to be a hashable type. Parameters ---------- values : str or sequence name(s) to set level : int, level name, or sequence of int/level names (default None) If the index is a MultiIndex (hierarchical), level(s) to set (None ...
return if the index is monotonic increasing (only equal or increasing) values. def is_monotonic_increasing(self): """ return if the index is monotonic increasing (only equal or increasing) values. """ # reversed() because lexsort() wants the most significant key last. ...
validate and return the hash for the provided key *this is internal for use for the cython routines* Parameters ---------- key : string or tuple Returns ------- np.uint64 Notes ----- we need to stringify if we have mixed levels def _ha...
Return vector of label values for requested level, equal to the length of the index **this is an internal method** Parameters ---------- level : int level unique : bool, default False if True, drop duplicated values Returns ------- v...
Return vector of label values for requested level, equal to the length of the index. Parameters ---------- level : int or str ``level`` is either the integer position of the level in the MultiIndex, or the name of the level. Returns ------- ...
Create a DataFrame with the levels of the MultiIndex as columns. Column ordering is determined by the DataFrame constructor with data as a dict. .. versionadded:: 0.24.0 Parameters ---------- index : boolean, default True Set the index of the returned DataF...
Return a MultiIndex reshaped to conform to the shapes given by n_repeat and n_shuffle. .. deprecated:: 0.24.0 Useful to replicate and rearrange a MultiIndex for combination with another Index with n_repeat items. Parameters ---------- n_repeat : int ...
.. versionadded:: 0.20.0 This is an *internal* function. Create a new MultiIndex from the current to monotonically sorted items IN the levels. This does not actually make the entire MultiIndex monotonic, JUST the levels. The resulting MultiIndex will have the same outward ...
Create a new MultiIndex from the current that removes unused levels, meaning that they are not expressed in the labels. The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the original. .. versionad...
Internal method to handle NA filling of take def _assert_take_fillable(self, values, indices, allow_fill=True, fill_value=None, na_value=None): """ Internal method to handle NA filling of take """ # only fill if we are passing a non-None fill_value if allow_fill an...
Append a collection of Index options together Parameters ---------- other : Index or list/tuple of indices Returns ------- appended : Index def append(self, other): """ Append a collection of Index options together Parameters ----------...
Make new MultiIndex with passed list of codes deleted Parameters ---------- codes : array-like Must be a list of tuples level : int or level name, default None Returns ------- dropped : MultiIndex def drop(self, codes, level=None, errors='raise'): ...
Swap level i with level j. Calling this method does not change the ordering of the values. Parameters ---------- i : int, str, default -2 First level of index to be swapped. Can pass level name as string. Type of parameters can be mixed. j : int, str, de...
Rearrange levels using input order. May not drop or duplicate levels Parameters ---------- def reorder_levels(self, order): """ Rearrange levels using input order. May not drop or duplicate levels Parameters ---------- """ order = [self._get_level_numbe...
we categorizing our codes by using the available categories (all, not just observed) excluding any missing ones (-1); this is in preparation for sorting, where we need to disambiguate that -1 is not a valid valid def _get_codes_for_sorting(self): """ we categorizing our ...
Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Parameters ---------- level : list-like, int or str, default 0 If a string is given, must be a name of the level If list-like must be nam...
Parameters ---------- keyarr : list-like Indexer to convert. Returns ------- tuple (indexer, keyarr) indexer is an ndarray or None if cannot convert keyarr are tuple-safe keys def _convert_listlike_indexer(self, keyarr, kind=None): ""...
Create index with target's values (move/add/delete values as necessary) Returns ------- new_index : pd.MultiIndex Resulting index indexer : np.ndarray or None Indices of output values in original index. def reindex(self, target, method=None, level=None, limit=No...
For an ordered MultiIndex, compute the slice locations for input labels. The input labels can be tuples representing partial levels, e.g. for a MultiIndex with 3 levels, you can pass a single value (corresponding to the first level), or a 1-, 2-, or 3-tuple. Parameters ...
Get location for a label or a tuple of labels as an integer, slice or boolean mask. Parameters ---------- key : label or tuple of labels (one for each level) method : None Returns ------- loc : int, slice object or boolean mask If the key is ...
Get both the location for the requested label(s) and the resulting sliced index. Parameters ---------- key : label or sequence of labels level : int/level name or list thereof, optional drop_level : bool, default True if ``False``, the resulting index will no...
Get location for a given label/slice/list/mask or a sequence of such as an array of integers. Parameters ---------- seq : label/slice/list/mask or a sequence of such You should use one of the above for each level. If a level should not be used, set it to ``slice(No...
Slice index between two labels / tuples, return new MultiIndex Parameters ---------- before : label or tuple, can be partial. Default None None defaults to start after : label or tuple, can be partial. Default None None defaults to end Returns --...
Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See Also -------- equal_levels def equals(self, other): """ Determines if two MultiIndex objects have the same labeling information ...
Return True if the levels of both MultiIndex objects are the same def equal_levels(self, other): """ Return True if the levels of both MultiIndex objects are the same """ if self.nlevels != other.nlevels: return False for i in range(self.nlevels): if no...
Form the union of two MultiIndex objects Parameters ---------- other : MultiIndex or array / Index of tuples sort : False or None, default None Whether to sort the resulting Index. * None : Sort the result, except when 1. `self` and `other` are eq...
Form the intersection of two MultiIndex objects. Parameters ---------- other : MultiIndex or array / Index of tuples sort : False or None, default False Sort the resulting MultiIndex if possible .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 ...
Compute set difference of two MultiIndex objects Parameters ---------- other : MultiIndex sort : False or None, default None Sort the resulting MultiIndex if possible .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the de...
Make new MultiIndex inserting new item at location Parameters ---------- loc : int item : tuple Must be same length as number of levels in the MultiIndex Returns ------- new_index : Index def insert(self, loc, item): """ Make new Mul...
Make new index with passed location deleted Returns ------- new_index : MultiIndex def delete(self, loc): """ Make new index with passed location deleted Returns ------- new_index : MultiIndex """ new_codes = [np.delete(level_codes, loc)...
routine to ensure that our data is of the correct input dtype for lower-level routines This will coerce: - ints -> int64 - uint -> uint64 - bool -> uint64 (TODO this should be uint8) - datetimelike -> i8 - datetime64tz -> i8 (in local tz) - categorical -> codes Parameters -----...
reverse of _ensure_data Parameters ---------- values : ndarray dtype : pandas_dtype original : ndarray-like Returns ------- Index for extension types, otherwise ndarray casted to dtype def _reconstruct_data(values, dtype, original): """ reverse of _ensure_data Parameters ...
ensure that we are arraylike if not already def _ensure_arraylike(values): """ ensure that we are arraylike if not already """ if not is_array_like(values): inferred = lib.infer_dtype(values, skipna=False) if inferred in ['mixed', 'string', 'unicode']: if isinstance(values, ...
Parameters ---------- values : arraylike Returns ------- tuples(hashtable class, vector class, values, dtype, ndtype) def _get_hashtable_algo(values): """ Parameters ---------- values : arraylike Returns ------- tuples(hashta...
Compute locations of to_match into values Parameters ---------- to_match : array-like values to find positions of values : array-like Unique set of values na_sentinel : int, default -1 Value to mark "not found" Examples -------- Returns ------- match : ...
Hash table-based unique. Uniques are returned in order of appearance. This does NOT sort. Significantly faster than numpy.unique. Includes NA values. Parameters ---------- values : 1d array-like Returns ------- numpy.ndarray or ExtensionArray The return can be: * Ind...
Compute the isin boolean array Parameters ---------- comps : array-like values : array-like Returns ------- boolean array same length as comps def isin(comps, values): """ Compute the isin boolean array Parameters ---------- comps : array-like values : array-like ...
Factorize an array-like to labels and uniques. This doesn't do any coercion of types or unboxing before factorization. Parameters ---------- values : ndarray na_sentinel : int, default -1 size_hint : int, optional Passsed through to the hashtable's 'get_labels' method na_value : ob...
Compute a histogram of the counts of non-null values. Parameters ---------- values : ndarray (1-d) sort : boolean, default True Sort by values ascending : boolean, default False Sort in ascending order normalize: boolean, default False If True then compute a relative his...
Parameters ---------- values : arraylike dropna : boolean Returns ------- (uniques, counts) def _value_counts_arraylike(values, dropna): """ Parameters ---------- values : arraylike dropna : boolean Returns ------- (uniques, counts) """ values = _ensur...
Return boolean ndarray denoting duplicate values. .. versionadded:: 0.19.0 Parameters ---------- values : ndarray-like Array over which to check for duplicate values. keep : {'first', 'last', False}, default 'first' - ``first`` : Mark duplicates as ``True`` except for the first ...
Returns the mode(s) of an array. Parameters ---------- values : array-like Array over which to check for duplicate values. dropna : boolean, default True Don't consider counts of NaN/NaT. .. versionadded:: 0.24.0 Returns ------- mode : Series def mode(values, drop...
Rank the values along a given axis. Parameters ---------- values : array-like Array whose values will be ranked. The number of dimensions in this array must not exceed 2. axis : int, default 0 Axis over which to perform rankings. method : {'average', 'min', 'max', 'first', '...
Perform array addition that checks for underflow and overflow. Performs the addition of an int64 array and an int64 integer (or array) but checks that they do not result in overflow first. For elements that are indicated to be NaN, whether or not there is overflow for that element is automatically igno...
Compute sample quantile or quantiles of the input array. For example, q=0.5 computes the median. The `interpolation_method` parameter supports three values, namely `fraction` (default), `lower` and `higher`. Interpolation is done only, if the desired quantile lies between two data points `i` and `j`. F...
Take elements from an array. .. versionadded:: 0.23.0 Parameters ---------- arr : sequence Non array-likes (sequences without a dtype) are coerced to an ndarray. indices : sequence of integers Indices to be taken. axis : int, default 0 The axis over which to sel...
Specialized Cython take which sets NaN values in one pass This dispatches to ``take`` defined on ExtensionArrays. It does not currently dispatch to ``SparseArray.take`` for sparse ``arr``. Parameters ---------- arr : array-like Input array. indexer : ndarray 1-D array of indice...
Specialized Cython take which sets NaN values in one pass def take_2d_multi(arr, indexer, out=None, fill_value=np.nan, mask_info=None, allow_fill=True): """ Specialized Cython take which sets NaN values in one pass """ if indexer is None or (indexer[0] is None and indexer[1] is None):...
Find indices where elements should be inserted to maintain order. .. versionadded:: 0.25.0 Find the indices into a sorted array `arr` (a) such that, if the corresponding elements in `value` were inserted before the indices, the order of `arr` would be preserved. Assuming that `arr` is sorted: ...
difference of n between self, analogous to s-s.shift(n) Parameters ---------- arr : ndarray n : int number of periods axis : int axis to shift on Returns ------- shifted def diff(arr, n, axis=0): """ difference of n between self, analogous to s-s.shift(...
For arbitrary (MultiIndexed) SparseSeries return (v, i, j, ilabels, jlabels) where (v, (i, j)) is suitable for passing to scipy.sparse.coo constructor. def _to_ijv(ss, row_levels=(0, ), column_levels=(1, ), sort_labels=False): """ For arbitrary (MultiIndexed) SparseSeries return (v, i, j, ilabels, jlab...
Convert a SparseSeries to a scipy.sparse.coo_matrix using index levels row_levels, column_levels as the row and column labels respectively. Returns the sparse_matrix, row and column labels. def _sparse_series_to_coo(ss, row_levels=(0, ), column_levels=(1, ), sort_labels=False): ""...
Convert a scipy.sparse.coo_matrix to a SparseSeries. Use the defaults given in the SparseSeries constructor. def _coo_to_sparse_series(A, dense_index=False): """ Convert a scipy.sparse.coo_matrix to a SparseSeries. Use the defaults given in the SparseSeries constructor. """ s = Series(A.data, M...
Timestamp-like => dt64 def _to_M8(key, tz=None): """ Timestamp-like => dt64 """ if not isinstance(key, Timestamp): # this also converts strings key = Timestamp(key) if key.tzinfo is not None and tz is not None: # Don't tz_localize(None) if key is already tz-aware ...
Wrap comparison operations to convert datetime-like to datetime64 def _dt_array_cmp(cls, op): """ Wrap comparison operations to convert datetime-like to datetime64 """ opname = '__{name}__'.format(name=op.__name__) nat_result = opname == '__ne__' def wrapper(self, other): if isinstance...
Parameters ---------- data : list-like dtype : dtype, str, or None, default None copy : bool, default False tz : tzinfo, str, or None, default None dayfirst : bool, default False yearfirst : bool, default False ambiguous : str, bool, or arraylike, default 'raise' See pandas._libs...