text
stringlengths
81
112k
Provide boxed values for a column. def _box_col_values(self, values, items): """ Provide boxed values for a column. """ klass = self._constructor_sliced return klass(values, index=self.index, name=items, fastpath=True)
Ensure that if we don't have an index, that we can create one from the passed value. def _ensure_valid_index(self, value): """ Ensure that if we don't have an index, that we can create one from the passed value. """ # GH5632, make sure that we are a Series convertible ...
Add series to DataFrame in specified column. If series is a numpy-array (not a Series/TimeSeries), it must be the same length as the DataFrames index or an error will be thrown. Series/TimeSeries will be conformed to the DataFrames index to ensure homogeneity. def _set_item(self, key,...
Insert column into DataFrame at specified location. Raises a ValueError if `column` is already contained in the DataFrame, unless `allow_duplicates` is set to True. Parameters ---------- loc : int Insertion index. Must verify 0 <= loc <= len(columns) column ...
r""" Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters ---------- **kwargs : dict of {str: callable or Series} The column names are...
Ensures new columns (which go into the BlockManager as new blocks) are always copied and converted into an array. Parameters ---------- key : object value : scalar, Series, or array-like broadcast : bool, default True If ``key`` matches multiple duplicate col...
Label-based "fancy indexing" function for DataFrame. Given equal-length arrays of row and column labels, return an array of the values corresponding to each (row, col) pair. Parameters ---------- row_labels : sequence The row labels to use for lookup col_lab...
We are guaranteed non-Nones in the axes. def _reindex_multi(self, axes, copy, fill_value): """ We are guaranteed non-Nones in the axes. """ new_index, row_indexer = self.index.reindex(axes['index']) new_columns, col_indexer = self.columns.reindex(axes['columns']) if ro...
Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. Parameters ...
Alter axes labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don't throw an error. See the :ref:`user guide <basics.rename>` for more. Parameters ---------- mapper : dict-like...
Set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it. Parameters ---------- keys : label or array-like or list ...
Reset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels. Parameters ---------- level : int, str, tuple, or list, default None Only remo...
Remove missing values. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 Determine if rows or columns which contain miss...
Return DataFrame with duplicate rows removed, optionally only considering certain columns. Indexes, including time indexes are ignored. Parameters ---------- subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicate...
Return boolean Series denoting duplicate rows, optionally only considering certain columns. Parameters ---------- subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns ...
Return the first `n` rows ordered by `columns` in descending order. Return the first `n` rows with the largest values in `columns`, in descending order. The columns that are not specified are returned as well, but not used for ordering. This method is equivalent to ``df.sort_va...
Return the first `n` rows ordered by `columns` in ascending order. Return the first `n` rows with the smallest values in `columns`, in ascending order. The columns that are not specified are returned as well, but not used for ordering. This method is equivalent to ``df.sort_val...
Swap levels i and j in a MultiIndex on a particular axis. Parameters ---------- i, j : int, string (can be mixed) Level of index to be swapped. Can pass level name as string. Returns ------- DataFrame .. versionchanged:: 0.18.1 The index...
Rearrange index levels using input order. May not drop or duplicate levels. Parameters ---------- order : list of int or list of str List representing new level order. Reference level by number (position) or by key (label). axis : int Where to...
Perform column-wise combine with another DataFrame. Combines a DataFrame with `other` DataFrame using `func` to element-wise combine columns. The row and column indexes of the resulting DataFrame will be the union of the two. Parameters ---------- other : DataFrame ...
Update null elements with value in the same location in `other`. Combine two DataFrame objects by filling null values in one DataFrame with non-null values from other DataFrame. The row and column indexes of the resulting DataFrame will be the union of the two. Parameters -----...
Modify in place using non-NA values from another DataFrame. Aligns on indices. There is no return value. Parameters ---------- other : DataFrame, or object coercible into a DataFrame Should have at least one matching index/column label with the original DataFram...
Stack the prescribed level(s) from columns to index. Return a reshaped DataFrame or Series having a multi-level index with one or more new inner-most levels compared to the current DataFrame. The new inner-most levels are created by pivoting the columns of the current dataframe: ...
Pivot a level of the (necessarily hierarchical) index labels, returning a DataFrame having a new level of column labels whose inner-most level consists of the pivoted index labels. If the index is not a MultiIndex, the output will be a Series (the analogue of stack when the columns are ...
First discrete difference of element. Calculates the difference of a DataFrame element compared with another element in the DataFrame (default is the element in the same column of the previous row). Parameters ---------- periods : int, default 1 Periods to s...
Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on def _gotitem(self, key: Union[str, List[str]], ...
Apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame's index (``axis=0``) or the DataFrame's columns (``axis=1``). By default (``result_type=None``), the final return type is inferred from the return type ...
Apply a function to a Dataframe elementwise. This method applies a function that accepts and returns a scalar to every element of a DataFrame. Parameters ---------- func : callable Python function, returns a single value from a single value. Returns ...
Append rows of `other` to the end of caller, returning a new object. Columns in `other` that are not in the caller are added as new columns. Parameters ---------- other : DataFrame or Series/dict-like object, or list of these The data to append. ignore_index : boole...
Join columns of another DataFrame. Join columns with `other` DataFrame either on index or on a key column. Efficiently join multiple DataFrame objects by index at once by passing a list. Parameters ---------- other : DataFrame, Series, or list of DataFrame I...
Round a DataFrame to a variable number of decimal places. Parameters ---------- decimals : int, dict, Series Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round ...
Compute pairwise correlation of columns, excluding NA/null values. Parameters ---------- method : {'pearson', 'kendall', 'spearman'} or callable * pearson : standard correlation coefficient * kendall : Kendall Tau correlation coefficient * spearman : Spearman...
Compute pairwise covariance of columns, excluding NA/null values. Compute the pairwise covariance among the series of a DataFrame. The returned data frame is the `covariance matrix <https://en.wikipedia.org/wiki/Covariance_matrix>`__ of the columns of the DataFrame. Both NA and...
Compute pairwise correlation between rows or columns of DataFrame with rows or columns of Series or DataFrame. DataFrames are first aligned along both axes before computing the correlations. Parameters ---------- other : DataFrame, Series Object with which to comput...
Count non-NA cells for each column or row. The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending on `pandas.options.mode.use_inf_as_na`) are considered NA. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 If 0 or 'index' counts...
Count distinct observations over requested axis. Return Series with number of distinct observations. Can ignore NaN values. .. versionadded:: 0.20.0 Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to use. 0 or 'index' for row...
Return index of first occurrence of minimum over requested axis. NA/null values are excluded. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 0 or 'index' for row-wise, 1 or 'columns' for column-wise skipna : boolean, default True E...
Let's be explicit about this. def _get_agg_axis(self, axis_num): """ Let's be explicit about this. """ if axis_num == 0: return self.columns elif axis_num == 1: return self.index else: raise ValueError('Axis must be 0 or 1 (got %r)' % ...
Get the mode(s) of each element along the selected axis. The mode of a set of values is the value that appears most often. It can be multiple values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to iterate over while searching for ...
Return values at the given quantile over requested axis. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value between 0 <= q <= 1, the quantile(s) to compute. axis : {0, 1, 'index', 'columns'} (default 0) Equals 0 or 'index' for row-wis...
Cast to DatetimeIndex of timestamps, at *beginning* of period. Parameters ---------- freq : str, default frequency of PeriodIndex Desired frequency. how : {'s', 'e', 'start', 'end'} Convention for converting period to timestamp; start of period vs. en...
Whether each element in the DataFrame is contained in values. Parameters ---------- values : iterable, Series, DataFrame or dict The result will only be true at a location if all the labels match. If `values` is a Series, that's the index. If `values` is a di...
Infer and return an integer array of the values. Parameters ---------- values : 1D list-like dtype : dtype, optional dtype to coerce copy : boolean, default False Returns ------- IntegerArray Raises ------ TypeError if incompatible types def integer_array(values, ...
Safely cast the values to the dtype if they are equivalent, meaning floats must be equivalent to the ints. def safe_cast(values, dtype, copy): """ Safely cast the values to the dtype if they are equivalent, meaning floats must be equivalent to the ints. """ try: return values....
Coerce the input values array to numpy arrays with a mask Parameters ---------- values : 1D list-like dtype : integer dtype mask : boolean 1D array, optional copy : boolean, default False if True, copy the input Returns ------- tuple of (values, mask) def coerce_to_array(v...
Construction from a string, raise a TypeError if not possible def construct_from_string(cls, string): """ Construction from a string, raise a TypeError if not possible """ if string == cls.name: return cls() raise TypeError("Cannot construct a '{}' fr...
coerce to an ndarary of object dtype def _coerce_to_ndarray(self): """ coerce to an ndarary of object dtype """ # TODO(jreback) make this better data = self._data.astype(object) data[self._mask] = self._na_value return data
Cast to a NumPy array or IntegerArray with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If False, a copy is made only i...
Returns a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Parameters ---------- dropna : boolean, default True Don't include counts of NaN. Returns ------- counts : Series See Also...
Return values for sorting. Returns ------- ndarray The transformed values should maintain the ordering between values within the array. See Also -------- ExtensionArray.argsort def _values_for_argsort(self) -> np.ndarray: """Return value...
Parameters ---------- result : array-like mask : array-like bool other : scalar or array-like op_name : str def _maybe_mask_result(self, result, mask, other, op_name): """ Parameters ---------- result : array-like mask : array-like bool ...
return the length of a single non-tuple indexer which could be a slice def length_of_indexer(indexer, target=None): """ return the length of a single non-tuple indexer which could be a slice """ if target is not None and isinstance(indexer, slice): target_len = len(target) start = index...
if we are index sliceable, then return my slicer, otherwise return None def convert_to_index_sliceable(obj, key): """ if we are index sliceable, then return my slicer, otherwise return None """ idx = obj.index if isinstance(key, slice): return idx._convert_slice_indexer(key, kind='getitem')...
Validate that value and indexer are the same length. An special-case is allowed for when the indexer is a boolean array and the number of true values equals the length of ``value``. In this case, no exception is raised. Parameters ---------- indexer : sequence The key for the setitem ...
reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted def convert_missing_indexer(indexer): """ reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted """ if isinstanc...
create a filtered indexer that doesn't have any missing indexers def convert_from_missing_indexer_tuple(indexer, axes): """ create a filtered indexer that doesn't have any missing indexers """ def get_indexer(_i, _idx): return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else ...
Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If we have indices that are out-of-bounds, raise an IndexError. Parameters ---------- indices : array-like The array of indices that we are to convert. n : int The ...
Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters ---------- indices : ndarray n : int length of the array being indexed Raises ------ ValueError Examples -------- >>> validate_indices([1, 2], 3) # OK >>> valid...
We likely want to take the cross-product def maybe_convert_ix(*args): """ We likely want to take the cross-product """ ixify = True for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): ixify = False if ixify: return np.ix_(*args) else:...
Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make sure we're always working with DataFrames. def _non_reducing_slice(slice_): """ Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have...
want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is passed go with that. def _maybe_numeric_slice(df, slice_, include_bool=False): """ want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is passed go with that....
check the key for valid keys across my indexer def _has_valid_tuple(self, key): """ check the key for valid keys across my indexer """ for i, k in enumerate(key): if i >= self.obj.ndim: raise IndexingError('Too many indexers') try: self._validate_...
validate that an positional indexer cannot enlarge its target will raise if needed, does not modify the indexer externally def _has_valid_positional_setitem_indexer(self, indexer): """ validate that an positional indexer cannot enlarge its target will raise if needed, does not modify the indexe...
Parameters ---------- indexer : tuple, slice, scalar The indexer used to get the locations that will be set to `ser` ser : pd.Series The values to assign to the locations specified by `indexer` multiindex_indexer : boolean, optional Defau...
Check whether there is the possibility to use ``_multi_take``. Currently the limit is that all axes being indexed must be indexed with list-likes. Parameters ---------- tup : tuple Tuple of indexers, one per axis Returns ------- boolean: Whet...
Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed all at once - rather than once for each dimension - improving efficiency. Parameters ---------- tup : tuple Tuple of indexers, one per axis...
Transform a list-like of keys into a new index and an indexer. Parameters ---------- key : list-like Target labels axis: int Dimension on which the indexing is being made raise_missing: bool Whether to raise a KeyError if some labels are not f...
Index current object with an an iterable key (which can be a boolean indexer, or a collection of keys). Parameters ---------- key : iterable Target labels, or boolean indexer axis: int, default None Dimension on which the indexing is being made R...
Check that indexer can be used to return a result (e.g. at least one element was found, unless the list of keys was actually empty). Parameters ---------- key : list-like Target labels (only used to show correct error message) indexer: array-like of booleans ...
Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? 'In the face of ambiguity, re...
Transform a list of keys into a new array ready to be used as axis of the object we return (e.g. including NaNs). Parameters ---------- key : list-like Target labels axis: int Where the indexing is being made Returns ------- list-...
this is pretty simple as we just have to deal with labels def _get_slice_axis(self, slice_obj, axis=None): """ this is pretty simple as we just have to deal with labels """ if axis is None: axis = self.axis or 0 obj = self.obj if not need_slice(slice_obj): retur...
Translate any partial string timestamp matches in key, returning the new key (GH 10331) def _get_partial_string_timestamp_match_key(self, key, labels): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): ...
Check that 'key' is a valid position in the desired axis. Parameters ---------- key : int Requested position axis : int Desired axis Returns ------- None Raises ------ IndexError If 'key' is not a vali...
Return Series values by list or array of integers Parameters ---------- key : list-like positional indexer axis : int (can only be zero) Returns ------- Series object def _get_list_axis(self, key, axis=None): """ Return Series values by list or ...
much simpler as we only have to deal with our valid types def _convert_to_indexer(self, obj, axis=None, is_setter=False): """ much simpler as we only have to deal with our valid types """ if axis is None: axis = self.axis or 0 # make need to convert a float key if isinstanc...
require they keys to be the same type as the index (so we don't fallback) def _convert_key(self, key, is_setter=False): """ require they keys to be the same type as the index (so we don't fallback) """ # allow arbitrary setting if is_setter: return list(key)...
require integer args (and convert to label arguments) def _convert_key(self, key, is_setter=False): """ require integer args (and convert to label arguments) """ for a, i in zip(self.obj.axes, key): if not is_integer(i): raise ValueError("iAt based indexing can only have int...
create and return the block manager from a dataframe of series, columns, index def to_manager(sdf, columns, index): """ create and return the block manager from a dataframe of series, columns, index """ # from BlockManager perspective axes = [ensure_index(columns), ensure_index(index)] re...
Only makes sense when fill_value is NaN def stack_sparse_frame(frame): """ Only makes sense when fill_value is NaN """ lengths = [s.sp_index.npoints for _, s in frame.items()] nobs = sum(lengths) # this is pretty fast minor_codes = np.repeat(np.arange(len(frame.columns)), lengths) ind...
Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex corresponding to the locations where they all have data Parameters ---------- series_dict : dict or DataFrame Notes ----- Using the dumbest algorithm I could think of. Should put some more thought into this ...
Init self from ndarray or list of lists. def _init_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists. """ data = prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) data = {idx: data[:, i] for i...
Init self from scipy.sparse matrix. def _init_spmatrix(self, data, index, columns, dtype=None, fill_value=None): """ Init self from scipy.sparse matrix. """ index, columns = self._prep_index(data, index, columns) data = data.tocoo() N = len(index) ...
Return the contents of the frame as a sparse SciPy COO matrix. .. versionadded:: 0.20.0 Returns ------- coo_matrix : scipy.sparse.spmatrix If the caller is heterogeneous and contains booleans or objects, the result will be of dtype=object. See Notes. No...
Original pickle format def _unpickle_sparse_frame_compat(self, state): """ Original pickle format """ series, cols, idx, fv, kind = state if not isinstance(cols, Index): # pragma: no cover from pandas.io.pickle import _unpickle_array columns = _unpickle...
Convert to dense DataFrame Returns ------- df : DataFrame def to_dense(self): """ Convert to dense DataFrame Returns ------- df : DataFrame """ data = {k: v.to_dense() for k, v in self.items()} return DataFrame(data, index=self.i...
Get new SparseDataFrame applying func to each columns def _apply_columns(self, func): """ Get new SparseDataFrame applying func to each columns """ new_data = {col: func(series) for col, series in self.items()} return self._constructor( data=new...
Make a copy of this SparseDataFrame def copy(self, deep=True): """ Make a copy of this SparseDataFrame """ result = super().copy(deep=deep) result._default_fill_value = self._default_fill_value result._default_kind = self._default_kind return result
Ratio of non-sparse points to total (dense) data points represented in the frame def density(self): """ Ratio of non-sparse points to total (dense) data points represented in the frame """ tot_nonsparse = sum(ser.sp_index.npoints for _, ser in...
Creates a new SparseArray from the input value. Parameters ---------- key : object value : scalar, Series, or array-like kwargs : dict Returns ------- sanitized_column : SparseArray def _sanitize_column(self, key, value, **kwargs): """ C...
Returns a row (cross-section) from the SparseDataFrame as a Series object. Parameters ---------- key : some index contained in the index Returns ------- xs : Series def xs(self, key, axis=0, copy=False): """ Returns a row (cross-section) from th...
Returns a DataFrame with the rows/columns switched. def transpose(self, *args, **kwargs): """ Returns a DataFrame with the rows/columns switched. """ nv.validate_transpose(args, kwargs) return self._constructor( self.values.T, index=self.columns, columns=self.index, ...
Return SparseDataFrame of cumulative sums over requested axis. Parameters ---------- axis : {0, 1} 0 for row-wise, 1 for column-wise Returns ------- y : SparseDataFrame def cumsum(self, axis=0, *args, **kwargs): """ Return SparseDataFrame of...
Analogous to DataFrame.apply, for SparseDataFrame Parameters ---------- func : function Function to apply to each column axis : {0, 1, 'index', 'columns'} broadcast : bool, default False For aggregation functions, return object of same size with values ...
Convert a conda package to its pip equivalent. In most cases they are the same, those are the exceptions: - Packages that should be excluded (in `EXCLUDE`) - Packages that should be renamed (in `RENAME`) - A package requiring a specific version, in conda is defined with a single equal (e.g. ``pan...
Generate the pip dependencies file from the conda file, or compare that they are synchronized (``compare=True``). Parameters ---------- conda_fname : str Path to the conda file with dependencies (e.g. `environment.yml`). pip_fname : str Path to the pip file with dependencies (e.g. `...
try to do platform conversion, allow ndarray or list here def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple)): values = construct_1d_object_array_from_listlike(list(values)) if getattr(values, 'dtype', None) == ...
return a boolean if we have a nested object, e.g. a Series with 1 or more Series elements This may not be necessarily be performant. def is_nested_object(obj): """ return a boolean if we have a nested object, e.g. a Series with 1 or more Series elements This may not be necessarily be performa...
try to cast to the specified dtype (e.g. convert back to bool/int or could be an astype of float64->float32 def maybe_downcast_to_dtype(result, dtype): """ try to cast to the specified dtype (e.g. convert back to bool/int or could be an astype of float64->float32 """ if is_scalar(result): ...
A safe version of putmask that potentially upcasts the result. The result is replaced with the first N elements of other, where N is the number of True values in mask. If the length of other is shorter than N, other will be repeated. Parameters ---------- result : ndarray The destinatio...