Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _set_item(self, key, value):
self._ensure_valid_index(value)
value = self._sanitize_column(key, value)
NDFrame._set_item(self, key, value)
# check if we are modifying a copy
# try to set first as we want an invalid
... | [
"\n Add series to DataFrame in specified column.\n\n If series is a numpy-array (not a Series/TimeSeries), it must be the\n same length as the DataFrames index or an error will be thrown.\n\n Series/TimeSeries will be conformed to the DataFrames index to\n ensure homogeneity.\n ... |
Please provide a description of the function:def insert(self, loc, column, value, allow_duplicates=False):
self._ensure_valid_index(value)
value = self._sanitize_column(column, value, broadcast=False)
self._data.insert(loc, column, value,
allow_duplicates=allow... | [
"\n Insert column into DataFrame at specified location.\n\n Raises a ValueError if `column` is already contained in the DataFrame,\n unless `allow_duplicates` is set to True.\n\n Parameters\n ----------\n loc : int\n Insertion index. Must verify 0 <= loc <= len(c... |
Please provide a description of the function:def assign(self, **kwargs):
r
data = self.copy()
# >= 3.6 preserve order of kwargs
if PY36:
for k, v in kwargs.items():
data[k] = com.apply_if_callable(v, data)
else:
# <= 3.5: do all calculatio... | [
"\n Assign new columns to a DataFrame.\n\n Returns a new object with all original columns in addition to new ones.\n Existing columns that are re-assigned will be overwritten.\n\n Parameters\n ----------\n **kwargs : dict of {str: callable or Series}\n The column... |
Please provide a description of the function:def _sanitize_column(self, key, value, broadcast=True):
def reindexer(value):
# reindex if necessary
if value.index.equals(self.index) or not len(self.index):
value = value._values.copy()
else:
... | [
"\n Ensures new columns (which go into the BlockManager as new blocks) are\n always copied and converted into an array.\n\n Parameters\n ----------\n key : object\n value : scalar, Series, or array-like\n broadcast : bool, default True\n If ``key`` matches... |
Please provide a description of the function:def lookup(self, row_labels, col_labels):
n = len(row_labels)
if n != len(col_labels):
raise ValueError('Row labels must have same size as column labels')
thresh = 1000
if not self._is_mixed_type or n > thresh:
... | [
"\n Label-based \"fancy indexing\" function for DataFrame.\n\n Given equal-length arrays of row and column labels, return an\n array of the values corresponding to each (row, col) pair.\n\n Parameters\n ----------\n row_labels : sequence\n The row labels to use f... |
Please provide a description of the function:def _reindex_multi(self, axes, copy, fill_value):
new_index, row_indexer = self.index.reindex(axes['index'])
new_columns, col_indexer = self.columns.reindex(axes['columns'])
if row_indexer is not None and col_indexer is not None:
... | [
"\n We are guaranteed non-Nones in the axes.\n "
] |
Please provide a description of the function:def drop(self, labels=None, axis=0, index=None, columns=None,
level=None, inplace=False, errors='raise'):
return super().drop(labels=labels, axis=axis, index=index,
columns=columns, level=level, inplace=inplace,
... | [
"\n Drop specified labels from rows or columns.\n\n Remove rows or columns by specifying label names and corresponding\n axis, or by specifying directly index or column names. When using a\n multi-index, labels on different levels can be removed by specifying\n the level.\n\n ... |
Please provide a description of the function:def rename(self, *args, **kwargs):
axes = validate_axis_style_args(self, args, kwargs, 'mapper', 'rename')
kwargs.update(axes)
# Pop these, since the values are in `kwargs` under different names
kwargs.pop('axis', None)
kwargs... | [
"\n Alter axes labels.\n\n Function / dict values must be unique (1-to-1). Labels not contained in\n a dict / Series will be left as-is. Extra labels listed don't throw an\n error.\n\n See the :ref:`user guide <basics.rename>` for more.\n\n Parameters\n ----------\n ... |
Please provide a description of the function:def set_index(self, keys, drop=True, append=False, inplace=False,
verify_integrity=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
if not isinstance(keys, list):
keys = [keys]
err_msg = ('The parameter... | [
"\n Set the DataFrame index using existing columns.\n\n Set the DataFrame index (row labels) using one or more existing\n columns or arrays (of the correct length). The index can replace the\n existing index or expand on it.\n\n Parameters\n ----------\n keys : label... |
Please provide a description of the function:def reset_index(self, level=None, drop=False, inplace=False, col_level=0,
col_fill=''):
inplace = validate_bool_kwarg(inplace, 'inplace')
if inplace:
new_obj = self
else:
new_obj = self.copy()
... | [
"\n Reset the index, or a level of it.\n\n Reset the index of the DataFrame, and use the default one instead.\n If the DataFrame has a MultiIndex, this method can remove one or more\n levels.\n\n Parameters\n ----------\n level : int, str, tuple, or list, default Non... |
Please provide a description of the function:def dropna(self, axis=0, how='any', thresh=None, subset=None,
inplace=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
if isinstance(axis, (tuple, list)):
# GH20987
msg = ("supplying multiple axes to ax... | [
"\n Remove missing values.\n\n See the :ref:`User Guide <missing_data>` for more on which values are\n considered missing, and how to work with missing data.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n Determine if rows or col... |
Please provide a description of the function:def drop_duplicates(self, subset=None, keep='first', inplace=False):
if self.empty:
return self.copy()
inplace = validate_bool_kwarg(inplace, 'inplace')
duplicated = self.duplicated(subset, keep=keep)
if inplace:
... | [
"\n Return DataFrame with duplicate rows removed, optionally only\n considering certain columns. Indexes, including time indexes\n are ignored.\n\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for... |
Please provide a description of the function:def duplicated(self, subset=None, keep='first'):
from pandas.core.sorting import get_group_index
from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT
if self.empty:
return Series(dtype=bool)
def f(vals):... | [
"\n Return boolean Series denoting duplicate rows, optionally only\n considering certain columns.\n\n Parameters\n ----------\n subset : column label or sequence of labels, optional\n Only consider certain columns for identifying duplicates, by\n default use ... |
Please provide a description of the function:def nlargest(self, n, columns, keep='first'):
return algorithms.SelectNFrame(self,
n=n,
keep=keep,
columns=columns).nlargest() | [
"\n Return the first `n` rows ordered by `columns` in descending order.\n\n Return the first `n` rows with the largest values in `columns`, in\n descending order. The columns that are not specified are returned as\n well, but not used for ordering.\n\n This method is equivalent to... |
Please provide a description of the function:def nsmallest(self, n, columns, keep='first'):
return algorithms.SelectNFrame(self,
n=n,
keep=keep,
columns=columns).nsmallest() | [
"\n Return the first `n` rows ordered by `columns` in ascending order.\n\n Return the first `n` rows with the smallest values in `columns`, in\n ascending order. The columns that are not specified are returned as\n well, but not used for ordering.\n\n This method is equivalent to\... |
Please provide a description of the function:def swaplevel(self, i=-2, j=-1, axis=0):
result = self.copy()
axis = self._get_axis_number(axis)
if axis == 0:
result.index = result.index.swaplevel(i, j)
else:
result.columns = result.columns.swaplevel(i, j)
... | [
"\n Swap levels i and j in a MultiIndex on a particular axis.\n\n Parameters\n ----------\n i, j : int, string (can be mixed)\n Level of index to be swapped. Can pass level name as string.\n\n Returns\n -------\n DataFrame\n\n .. versionchanged:: 0.... |
Please provide a description of the function:def reorder_levels(self, order, axis=0):
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis),
MultiIndex): # pragma: no cover
raise TypeError('Can only reorder levels on a hierarchical axis... | [
"\n Rearrange index levels using input order. May not drop or\n duplicate levels.\n\n Parameters\n ----------\n order : list of int or list of str\n List representing new level order. Reference level by number\n (position) or by key (label).\n axis : i... |
Please provide a description of the function:def combine(self, other, func, fill_value=None, overwrite=True):
other_idxlen = len(other.index) # save for compare
this, other = self.align(other, copy=False)
new_index = this.index
if other.empty and len(new_index) == len(self.in... | [
"\n Perform column-wise combine with another DataFrame.\n\n Combines a DataFrame with `other` DataFrame using `func`\n to element-wise combine columns. The row and column indexes of the\n resulting DataFrame will be the union of the two.\n\n Parameters\n ----------\n ... |
Please provide a description of the function:def combine_first(self, other):
import pandas.core.computation.expressions as expressions
def extract_values(arr):
# Does two things:
# 1. maybe gets the values from the Series / Index
# 2. convert datelike to i8
... | [
"\n Update null elements with value in the same location in `other`.\n\n Combine two DataFrame objects by filling null values in one DataFrame\n with non-null values from other DataFrame. The row and column indexes\n of the resulting DataFrame will be the union of the two.\n\n Par... |
Please provide a description of the function:def update(self, other, join='left', overwrite=True, filter_func=None,
errors='ignore'):
import pandas.core.computation.expressions as expressions
# TODO: Support other joins
if join != 'left': # pragma: no cover
r... | [
"\n Modify in place using non-NA values from another DataFrame.\n\n Aligns on indices. There is no return value.\n\n Parameters\n ----------\n other : DataFrame, or object coercible into a DataFrame\n Should have at least one matching index/column label\n wit... |
Please provide a description of the function:def stack(self, level=-1, dropna=True):
from pandas.core.reshape.reshape import stack, stack_multiple
if isinstance(level, (tuple, list)):
return stack_multiple(self, level, dropna=dropna)
else:
return stack(self, lev... | [
"\n Stack the prescribed level(s) from columns to index.\n\n Return a reshaped DataFrame or Series having a multi-level\n index with one or more new inner-most levels compared to the current\n DataFrame. The new inner-most levels are created by pivoting the\n columns of the curren... |
Please provide a description of the function:def unstack(self, level=-1, fill_value=None):
from pandas.core.reshape.reshape import unstack
return unstack(self, level, fill_value) | [
"\n Pivot a level of the (necessarily hierarchical) index labels, returning\n a DataFrame having a new level of column labels whose inner-most level\n consists of the pivoted index labels.\n\n If the index is not a MultiIndex, the output will be a Series\n (the analogue of stack w... |
Please provide a description of the function:def diff(self, periods=1, axis=0):
bm_axis = self._get_block_manager_axis(axis)
new_data = self._data.diff(n=periods, axis=bm_axis)
return self._constructor(new_data) | [
"\n First discrete difference of element.\n\n Calculates the difference of a DataFrame element compared with another\n element in the DataFrame (default is the element in the same column\n of the previous row).\n\n Parameters\n ----------\n periods : int, default 1\n... |
Please provide a description of the function:def _gotitem(self,
key: Union[str, List[str]],
ndim: int,
subset: Optional[Union[Series, ABCDataFrame]] = None,
) -> Union[Series, ABCDataFrame]:
if subset is None:
subset = self... | [
"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n "
] |
Please provide a description of the function:def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
result_type=None, args=(), **kwds):
from pandas.core.apply import frame_apply
op = frame_apply(self,
func=func,
axis... | [
"\n Apply a function along an axis of the DataFrame.\n\n Objects passed to the function are Series objects whose index is\n either the DataFrame's index (``axis=0``) or the DataFrame's columns\n (``axis=1``). By default (``result_type=None``), the final return type\n is inferred f... |
Please provide a description of the function:def applymap(self, func):
# if we have a dtype == 'M8[ns]', provide boxed values
def infer(x):
if x.empty:
return lib.map_infer(x, func)
return lib.map_infer(x.astype(object).values, func)
return self... | [
"\n Apply a function to a Dataframe elementwise.\n\n This method applies a function that accepts and returns a scalar\n to every element of a DataFrame.\n\n Parameters\n ----------\n func : callable\n Python function, returns a single value from a single value.\n... |
Please provide a description of the function:def append(self, other, ignore_index=False,
verify_integrity=False, sort=None):
if isinstance(other, (Series, dict)):
if isinstance(other, dict):
other = Series(other)
if other.name is None and not ignor... | [
"\n Append rows of `other` to the end of caller, returning a new object.\n\n Columns in `other` that are not in the caller are added as new columns.\n\n Parameters\n ----------\n other : DataFrame or Series/dict-like object, or list of these\n The data to append.\n ... |
Please provide a description of the function:def join(self, other, on=None, how='left', lsuffix='', rsuffix='',
sort=False):
# For SparseDataFrame's benefit
return self._join_compat(other, on=on, how=how, lsuffix=lsuffix,
rsuffix=rsuffix, sort=sort) | [
"\n Join columns of another DataFrame.\n\n Join columns with `other` DataFrame either on index or on a key\n column. Efficiently join multiple DataFrame objects by index at once by\n passing a list.\n\n Parameters\n ----------\n other : DataFrame, Series, or list of ... |
Please provide a description of the function:def round(self, decimals=0, *args, **kwargs):
from pandas.core.reshape.concat import concat
def _dict_round(df, decimals):
for col, vals in df.iteritems():
try:
yield _series_round(vals, decimals[col])... | [
"\n Round a DataFrame to a variable number of decimal places.\n\n Parameters\n ----------\n decimals : int, dict, Series\n Number of decimal places to round each column to. If an int is\n given, round each column to the same number of places.\n Otherwise ... |
Please provide a description of the function:def corr(self, method='pearson', min_periods=1):
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.values
if method == 'pearson':
correl = libalgos.nancorr(ensure_f... | [
"\n Compute pairwise correlation of columns, excluding NA/null values.\n\n Parameters\n ----------\n method : {'pearson', 'kendall', 'spearman'} or callable\n * pearson : standard correlation coefficient\n * kendall : Kendall Tau correlation coefficient\n ... |
Please provide a description of the function:def corrwith(self, other, axis=0, drop=False, method='pearson'):
axis = self._get_axis_number(axis)
this = self._get_numeric_data()
if isinstance(other, Series):
return this.apply(lambda x: other.corr(x, method=method),
... | [
"\n Compute pairwise correlation between rows or columns of DataFrame\n with rows or columns of Series or DataFrame. DataFrames are first\n aligned along both axes before computing the correlations.\n\n Parameters\n ----------\n other : DataFrame, Series\n Objec... |
Please provide a description of the function:def count(self, axis=0, level=None, numeric_only=False):
axis = self._get_axis_number(axis)
if level is not None:
return self._count_level(level, axis=axis,
numeric_only=numeric_only)
if numer... | [
"\n Count non-NA cells for each column or row.\n\n The values `None`, `NaN`, `NaT`, and optionally `numpy.inf` (depending\n on `pandas.options.mode.use_inf_as_na`) are considered NA.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n ... |
Please provide a description of the function:def nunique(self, axis=0, dropna=True):
return self.apply(Series.nunique, axis=axis, dropna=dropna) | [
"\n Count distinct observations over requested axis.\n\n Return Series with number of distinct observations. Can ignore NaN\n values.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to ... |
Please provide a description of the function:def idxmin(self, axis=0, skipna=True):
axis = self._get_axis_number(axis)
indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna)
index = self._get_axis(axis)
result = [index[i] if i >= 0 else np.nan for i in indices]
... | [
"\n Return index of first occurrence of minimum over requested axis.\n NA/null values are excluded.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n 0 or 'index' for row-wise, 1 or 'columns' for column-wise\n skipna : boolean, defa... |
Please provide a description of the function:def _get_agg_axis(self, axis_num):
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)' % axis_num) | [
"\n Let's be explicit about this.\n "
] |
Please provide a description of the function:def mode(self, axis=0, numeric_only=False, dropna=True):
data = self if not numeric_only else self._get_numeric_data()
def f(s):
return s.mode(dropna=dropna)
return data.apply(f, axis=axis) | [
"\n Get the mode(s) of each element along the selected axis.\n\n The mode of a set of values is the value that appears most often.\n It can be multiple values.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis to iterate ov... |
Please provide a description of the function:def quantile(self, q=0.5, axis=0, numeric_only=True,
interpolation='linear'):
self._check_percentile(q)
data = self._get_numeric_data() if numeric_only else self
axis = self._get_axis_number(axis)
is_transposed = axi... | [
"\n Return values at the given quantile over requested axis.\n\n Parameters\n ----------\n q : float or array-like, default 0.5 (50% quantile)\n Value between 0 <= q <= 1, the quantile(s) to compute.\n axis : {0, 1, 'index', 'columns'} (default 0)\n Equals 0 ... |
Please provide a description of the function:def to_timestamp(self, freq=None, how='start', axis=0, copy=True):
new_data = self._data
if copy:
new_data = new_data.copy()
axis = self._get_axis_number(axis)
if axis == 0:
new_data.set_axis(1, self.index.to_... | [
"\n Cast to DatetimeIndex of timestamps, at *beginning* of period.\n\n Parameters\n ----------\n freq : str, default frequency of PeriodIndex\n Desired frequency.\n how : {'s', 'e', 'start', 'end'}\n Convention for converting period to timestamp; start of per... |
Please provide a description of the function:def isin(self, values):
if isinstance(values, dict):
from pandas.core.reshape.concat import concat
values = collections.defaultdict(list, values)
return concat((self.iloc[:, [i]].isin(values[col])
... | [
"\n Whether each element in the DataFrame is contained in values.\n\n Parameters\n ----------\n values : iterable, Series, DataFrame or dict\n The result will only be true at a location if all the\n labels match. If `values` is a Series, that's the index. If\n ... |
Please provide a description of the function:def integer_array(values, dtype=None, copy=False):
values, mask = coerce_to_array(values, dtype=dtype, copy=copy)
return IntegerArray(values, mask) | [
"\n Infer and return an integer array of the values.\n\n Parameters\n ----------\n values : 1D list-like\n dtype : dtype, optional\n dtype to coerce\n copy : boolean, default False\n\n Returns\n -------\n IntegerArray\n\n Raises\n ------\n TypeError if incompatible types\n... |
Please provide a description of the function:def safe_cast(values, dtype, copy):
try:
return values.astype(dtype, casting='safe', copy=copy)
except TypeError:
casted = values.astype(dtype, copy=copy)
if (casted == values).all():
return casted
raise TypeError("... | [
"\n Safely cast the values to the dtype if they\n are equivalent, meaning floats must be equivalent to the\n ints.\n\n "
] |
Please provide a description of the function:def coerce_to_array(values, dtype, mask=None, copy=False):
# if values is integer numpy array, preserve it's dtype
if dtype is None and hasattr(values, 'dtype'):
if is_integer_dtype(values.dtype):
dtype = values.dtype
if dtype is not Non... | [
"\n Coerce the input values array to numpy arrays with a mask\n\n Parameters\n ----------\n values : 1D list-like\n dtype : integer dtype\n mask : boolean 1D array, optional\n copy : boolean, default False\n if True, copy the input\n\n Returns\n -------\n tuple of (values, mask)... |
Please provide a description of the function:def construct_from_string(cls, string):
if string == cls.name:
return cls()
raise TypeError("Cannot construct a '{}' from "
"'{}'".format(cls, string)) | [
"\n Construction from a string, raise a TypeError if not\n possible\n "
] |
Please provide a description of the function:def _coerce_to_ndarray(self):
# TODO(jreback) make this better
data = self._data.astype(object)
data[self._mask] = self._na_value
return data | [
"\n coerce to an ndarary of object dtype\n "
] |
Please provide a description of the function:def astype(self, dtype, copy=True):
# if we are astyping to an existing IntegerDtype we can fastpath
if isinstance(dtype, _IntegerDtype):
result = self._data.astype(dtype.numpy_dtype, copy=False)
return type(self)(result, mas... | [
"\n Cast to a NumPy array or IntegerArray with 'dtype'.\n\n Parameters\n ----------\n dtype : str or dtype\n Typecode or data-type to which the array is cast.\n copy : bool, default True\n Whether to copy the data, even if not necessary. If False,\n ... |
Please provide a description of the function:def value_counts(self, dropna=True):
from pandas import Index, Series
# compute counts on the data with no nans
data = self._data[~self._mask]
value_counts = Index(data).value_counts()
array = value_counts.values
# ... | [
"\n Returns a Series containing counts of each category.\n\n Every category will have an entry, even those with a count of 0.\n\n Parameters\n ----------\n dropna : boolean, default True\n Don't include counts of NaN.\n\n Returns\n -------\n counts ... |
Please provide a description of the function:def _values_for_argsort(self) -> np.ndarray:
data = self._data.copy()
data[self._mask] = data.min() - 1
return data | [
"Return values for sorting.\n\n Returns\n -------\n ndarray\n The transformed values should maintain the ordering between values\n within the array.\n\n See Also\n --------\n ExtensionArray.argsort\n "
] |
Please provide a description of the function:def _maybe_mask_result(self, result, mask, other, op_name):
# may need to fill infs
# and mask wraparound
if is_float_dtype(result):
mask |= (result == np.inf) | (result == -np.inf)
# if we have a float operand we are by... | [
"\n Parameters\n ----------\n result : array-like\n mask : array-like bool\n other : scalar or array-like\n op_name : str\n "
] |
Please provide a description of the function:def length_of_indexer(indexer, target=None):
if target is not None and isinstance(indexer, slice):
target_len = len(target)
start = indexer.start
stop = indexer.stop
step = indexer.step
if start is None:
start = 0
... | [
"\n return the length of a single non-tuple indexer which could be a slice\n "
] |
Please provide a description of the function:def convert_to_index_sliceable(obj, key):
idx = obj.index
if isinstance(key, slice):
return idx._convert_slice_indexer(key, kind='getitem')
elif isinstance(key, str):
# we are an actual column
if obj._data.items.contains(key):
... | [
"\n if we are index sliceable, then return my slicer, otherwise return None\n "
] |
Please provide a description of the function:def check_setitem_lengths(indexer, value, values):
# boolean with truth values == len of the value is ok too
if isinstance(indexer, (np.ndarray, list)):
if is_list_like(value) and len(indexer) != len(value):
if not (isinstance(indexer, np.nda... | [
"\n Validate that value and indexer are the same length.\n\n An special-case is allowed for when the indexer is a boolean array\n and the number of true values equals the length of ``value``. In\n this case, no exception is raised.\n\n Parameters\n ----------\n indexer : sequence\n The k... |
Please provide a description of the function:def convert_missing_indexer(indexer):
if isinstance(indexer, dict):
# a missing key (but not a tuple indexer)
indexer = indexer['key']
if isinstance(indexer, bool):
raise KeyError("cannot use a single bool to index into setitem... | [
"\n reverse convert a missing indexer, which is a dict\n return the scalar indexer and a boolean indicating if we converted\n "
] |
Please provide a description of the function:def convert_from_missing_indexer_tuple(indexer, axes):
def get_indexer(_i, _idx):
return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else
_idx)
return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(indexer)) | [
"\n create a filtered indexer that doesn't have any missing indexers\n "
] |
Please provide a description of the function:def maybe_convert_indices(indices, n):
if isinstance(indices, list):
indices = np.array(indices)
if len(indices) == 0:
# If list is empty, np.array will return float and cause indexing
# errors.
return np.empty(0,... | [
"\n Attempt to convert indices into valid, positive indices.\n\n If we have negative indices, translate to positive here.\n If we have indices that are out-of-bounds, raise an IndexError.\n\n Parameters\n ----------\n indices : array-like\n The array of indices that we are to convert.\n ... |
Please provide a description of the function:def validate_indices(indices, n):
if len(indices):
min_idx = indices.min()
if min_idx < -1:
msg = ("'indices' contains values less than allowed ({} < {})"
.format(min_idx, -1))
raise ValueError(msg)
... | [
"\n Perform bounds-checking for an indexer.\n\n -1 is allowed for indicating missing values.\n\n Parameters\n ----------\n indices : ndarray\n n : int\n length of the array being indexed\n\n Raises\n ------\n ValueError\n\n Examples\n --------\n >>> validate_indices([1, 2]... |
Please provide a description of the function:def maybe_convert_ix(*args):
ixify = True
for arg in args:
if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)):
ixify = False
if ixify:
return np.ix_(*args)
else:
return args | [
"\n We likely want to take the cross-product\n "
] |
Please provide a description of the function:def _non_reducing_slice(slice_):
# default to column slice, like DataFrame
# ['A', 'B'] -> IndexSlices[:, ['A', 'B']]
kinds = (ABCSeries, np.ndarray, Index, list, str)
if isinstance(slice_, kinds):
slice_ = IndexSlice[:, slice_]
def pred(par... | [
"\n Ensurse that a slice doesn't reduce to a Series or Scalar.\n\n Any user-paseed `subset` should have this called on it\n to make sure we're always working with DataFrames.\n "
] |
Please provide a description of the function:def _maybe_numeric_slice(df, slice_, include_bool=False):
if slice_ is None:
dtypes = [np.number]
if include_bool:
dtypes.append(bool)
slice_ = IndexSlice[:, df.select_dtypes(include=dtypes).columns]
return slice_ | [
"\n want nice defaults for background_gradient that don't break\n with non-numeric data. But if slice_ is passed go with that.\n "
] |
Please provide a description of the function:def _has_valid_tuple(self, key):
for i, k in enumerate(key):
if i >= self.obj.ndim:
raise IndexingError('Too many indexers')
try:
self._validate_key(k, i)
except ValueError:
... | [
" check the key for valid keys across my indexer "
] |
Please provide a description of the function:def _has_valid_positional_setitem_indexer(self, indexer):
if isinstance(indexer, dict):
raise IndexError("{0} cannot enlarge its target object"
.format(self.name))
else:
if not isinstance(indexer, ... | [
" validate that an positional indexer cannot enlarge its target\n will raise if needed, does not modify the indexer externally\n "
] |
Please provide a description of the function:def _align_series(self, indexer, ser, multiindex_indexer=False):
if isinstance(indexer, (slice, np.ndarray, list, Index)):
indexer = tuple([indexer])
if isinstance(indexer, tuple):
# flatten np.ndarray indexers
d... | [
"\n Parameters\n ----------\n indexer : tuple, slice, scalar\n The indexer used to get the locations that will be set to\n `ser`\n\n ser : pd.Series\n The values to assign to the locations specified by `indexer`\n\n multiindex_indexer : boolean, op... |
Please provide a description of the function:def _multi_take_opportunity(self, tup):
if not all(is_list_like_indexer(x) for x in tup):
return False
# just too complicated
if any(com.is_bool_indexer(x) for x in tup):
return False
return True | [
"\n Check whether there is the possibility to use ``_multi_take``.\n Currently the limit is that all axes being indexed must be indexed with\n list-likes.\n\n Parameters\n ----------\n tup : tuple\n Tuple of indexers, one per axis\n\n Returns\n ----... |
Please provide a description of the function:def _multi_take(self, tup):
# GH 836
o = self.obj
d = {axis: self._get_listlike_indexer(key, axis)
for (key, axis) in zip(tup, o._AXIS_ORDERS)}
return o._reindex_with_indexers(d, copy=True, allow_dups=True) | [
"\n Create the indexers for the passed tuple of keys, and execute the take\n operation. This allows the take operation to be executed all at once -\n rather than once for each dimension - improving efficiency.\n\n Parameters\n ----------\n tup : tuple\n Tuple of ... |
Please provide a description of the function:def _get_listlike_indexer(self, key, axis, raise_missing=False):
o = self.obj
ax = o._get_axis(axis)
# Have the index compute an indexer or return None
# if it cannot handle:
indexer, keyarr = ax._convert_listlike_indexer(key... | [
"\n Transform a list-like of keys into a new index and an indexer.\n\n Parameters\n ----------\n key : list-like\n Target labels\n axis: int\n Dimension on which the indexing is being made\n raise_missing: bool\n Whether to raise a KeyError ... |
Please provide a description of the function:def _getitem_iterable(self, key, axis=None):
if axis is None:
axis = self.axis or 0
self._validate_key(key, axis)
labels = self.obj._get_axis(axis)
if com.is_bool_indexer(key):
# A boolean indexer
... | [
"\n Index current object with an an iterable key (which can be a boolean\n indexer, or a collection of keys).\n\n Parameters\n ----------\n key : iterable\n Target labels, or boolean indexer\n axis: int, default None\n Dimension on which the indexing i... |
Please provide a description of the function:def _validate_read_indexer(self, key, indexer, axis, raise_missing=False):
ax = self.obj._get_axis(axis)
if len(key) == 0:
return
# Count missing values:
missing = (indexer < 0).sum()
if missing:
if... | [
"\n Check that indexer can be used to return a result (e.g. at least one\n element was found, unless the list of keys was actually empty).\n\n Parameters\n ----------\n key : list-like\n Target labels (only used to show correct error message)\n indexer: array-lik... |
Please provide a description of the function:def _convert_to_indexer(self, obj, axis=None, is_setter=False,
raise_missing=False):
if axis is None:
axis = self.axis or 0
labels = self.obj._get_axis(axis)
if isinstance(obj, slice):
ret... | [
"\n Convert indexing key into something we can use to do actual fancy\n indexing on an ndarray\n\n Examples\n ix[:5] -> slice(0, 5)\n ix[[1,2,3]] -> [1,2,3]\n ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz)\n\n Going by Zen of Python?\n 'In t... |
Please provide a description of the function:def _convert_for_reindex(self, key, axis=None):
if axis is None:
axis = self.axis or 0
labels = self.obj._get_axis(axis)
if com.is_bool_indexer(key):
key = check_bool_indexer(labels, key)
return labels[ke... | [
"\n Transform a list of keys into a new array ready to be used as axis of\n the object we return (e.g. including NaNs).\n\n Parameters\n ----------\n key : list-like\n Target labels\n axis: int\n Where the indexing is being made\n\n Returns\n ... |
Please provide a description of the function:def _get_slice_axis(self, slice_obj, axis=None):
if axis is None:
axis = self.axis or 0
obj = self.obj
if not need_slice(slice_obj):
return obj.copy(deep=False)
labels = obj._get_axis(axis)
indexer = ... | [
" this is pretty simple as we just have to deal with labels "
] |
Please provide a description of the function:def _get_partial_string_timestamp_match_key(self, key, labels):
if isinstance(labels, MultiIndex):
if (isinstance(key, str) and labels.levels[0].is_all_dates):
# Convert key '2016-01-01' to
# ('2016-01-01'[, slice(... | [
"Translate any partial string timestamp matches in key, returning the\n new key (GH 10331)"
] |
Please provide a description of the function:def _validate_integer(self, key, axis):
len_axis = len(self.obj._get_axis(axis))
if key >= len_axis or key < -len_axis:
raise IndexError("single positional indexer is out-of-bounds") | [
"\n Check that 'key' is a valid position in the desired axis.\n\n Parameters\n ----------\n key : int\n Requested position\n axis : int\n Desired axis\n\n Returns\n -------\n None\n\n Raises\n ------\n IndexError\n ... |
Please provide a description of the function:def _get_list_axis(self, key, axis=None):
if axis is None:
axis = self.axis or 0
try:
return self.obj._take(key, axis=axis)
except IndexError:
# re-raise with different error message
raise Index... | [
"\n Return Series values by list or array of integers\n\n Parameters\n ----------\n key : list-like positional indexer\n axis : int (can only be zero)\n\n Returns\n -------\n Series object\n "
] |
Please provide a description of the function:def _convert_to_indexer(self, obj, axis=None, is_setter=False):
if axis is None:
axis = self.axis or 0
# make need to convert a float key
if isinstance(obj, slice):
return self._convert_slice_indexer(obj, axis)
... | [
" much simpler as we only have to deal with our valid types "
] |
Please provide a description of the function:def _convert_key(self, key, is_setter=False):
# allow arbitrary setting
if is_setter:
return list(key)
for ax, i in zip(self.obj.axes, key):
if ax.is_integer():
if not is_integer(i):
... | [
" require they keys to be the same type as the index (so we don't\n fallback)\n "
] |
Please provide a description of the function:def _convert_key(self, key, is_setter=False):
for a, i in zip(self.obj.axes, key):
if not is_integer(i):
raise ValueError("iAt based indexing can only have integer "
"indexers")
return key | [
" require integer args (and convert to label arguments) "
] |
Please provide a description of the function:def to_manager(sdf, columns, index):
# from BlockManager perspective
axes = [ensure_index(columns), ensure_index(index)]
return create_block_manager_from_arrays(
[sdf[c] for c in columns], columns, axes) | [
" create and return the block manager from a dataframe of series,\n columns, index\n "
] |
Please provide a description of the function:def stack_sparse_frame(frame):
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)
inds_to_concat = []
vals_to_concat = []
# TODO... | [
"\n Only makes sense when fill_value is NaN\n "
] |
Please provide a description of the function:def homogenize(series_dict):
index = None
need_reindex = False
for _, series in series_dict.items():
if not np.isnan(series.fill_value):
raise TypeError('this method is only valid with NaN fill values')
if index is None:
... | [
"\n Conform a set of SparseSeries (with NaN fill_value) to a common SparseIndex\n corresponding to the locations where they all have data\n\n Parameters\n ----------\n series_dict : dict or DataFrame\n\n Notes\n -----\n Using the dumbest algorithm I could think of. Should put some more thoug... |
Please provide a description of the function:def _init_matrix(self, data, index, columns, dtype=None):
data = prep_ndarray(data, copy=False)
index, columns = self._prep_index(data, index, columns)
data = {idx: data[:, i] for i, idx in enumerate(columns)}
return self._init_dict(d... | [
"\n Init self from ndarray or list of lists.\n "
] |
Please provide a description of the function:def _init_spmatrix(self, data, index, columns, dtype=None,
fill_value=None):
index, columns = self._prep_index(data, index, columns)
data = data.tocoo()
N = len(index)
# Construct a dict of SparseSeries
... | [
"\n Init self from scipy.sparse matrix.\n "
] |
Please provide a description of the function:def to_coo(self):
try:
from scipy.sparse import coo_matrix
except ImportError:
raise ImportError('Scipy is not installed')
dtype = find_common_type(self.dtypes)
if isinstance(dtype, SparseDtype):
d... | [
"\n Return the contents of the frame as a sparse SciPy COO matrix.\n\n .. versionadded:: 0.20.0\n\n Returns\n -------\n coo_matrix : scipy.sparse.spmatrix\n If the caller is heterogeneous and contains booleans or objects,\n the result will be of dtype=object.... |
Please provide a description of the function:def _unpickle_sparse_frame_compat(self, state):
series, cols, idx, fv, kind = state
if not isinstance(cols, Index): # pragma: no cover
from pandas.io.pickle import _unpickle_array
columns = _unpickle_array(cols)
else... | [
"\n Original pickle format\n "
] |
Please provide a description of the function:def to_dense(self):
data = {k: v.to_dense() for k, v in self.items()}
return DataFrame(data, index=self.index, columns=self.columns) | [
"\n Convert to dense DataFrame\n\n Returns\n -------\n df : DataFrame\n "
] |
Please provide a description of the function:def _apply_columns(self, func):
new_data = {col: func(series)
for col, series in self.items()}
return self._constructor(
data=new_data, index=self.index, columns=self.columns,
default_fill_value=self.defa... | [
"\n Get new SparseDataFrame applying func to each columns\n "
] |
Please provide a description of the function:def copy(self, deep=True):
result = super().copy(deep=deep)
result._default_fill_value = self._default_fill_value
result._default_kind = self._default_kind
return result | [
"\n Make a copy of this SparseDataFrame\n "
] |
Please provide a description of the function:def density(self):
tot_nonsparse = sum(ser.sp_index.npoints
for _, ser in self.items())
tot = len(self.index) * len(self.columns)
return tot_nonsparse / float(tot) | [
"\n Ratio of non-sparse points to total (dense) data points\n represented in the frame\n "
] |
Please provide a description of the function:def _sanitize_column(self, key, value, **kwargs):
def sp_maker(x, index=None):
return SparseArray(x, index=index,
fill_value=self._default_fill_value,
kind=self._default_kind)
... | [
"\n Creates a new SparseArray from the input value.\n\n Parameters\n ----------\n key : object\n value : scalar, Series, or array-like\n kwargs : dict\n\n Returns\n -------\n sanitized_column : SparseArray\n\n "
] |
Please provide a description of the function:def xs(self, key, axis=0, copy=False):
if axis == 1:
data = self[key]
return data
i = self.index.get_loc(key)
data = self.take([i]).get_values()[0]
return Series(data, index=self.columns) | [
"\n Returns a row (cross-section) from the SparseDataFrame as a Series\n object.\n\n Parameters\n ----------\n key : some index contained in the index\n\n Returns\n -------\n xs : Series\n "
] |
Please provide a description of the function:def transpose(self, *args, **kwargs):
nv.validate_transpose(args, kwargs)
return self._constructor(
self.values.T, index=self.columns, columns=self.index,
default_fill_value=self._default_fill_value,
default_kind=s... | [
"\n Returns a DataFrame with the rows/columns switched.\n "
] |
Please provide a description of the function:def cumsum(self, axis=0, *args, **kwargs):
nv.validate_cumsum(args, kwargs)
if axis is None:
axis = self._stat_axis_number
return self.apply(lambda x: x.cumsum(), axis=axis) | [
"\n Return SparseDataFrame of cumulative sums over requested axis.\n\n Parameters\n ----------\n axis : {0, 1}\n 0 for row-wise, 1 for column-wise\n\n Returns\n -------\n y : SparseDataFrame\n "
] |
Please provide a description of the function:def apply(self, func, axis=0, broadcast=None, reduce=None,
result_type=None):
if not len(self.columns):
return self
axis = self._get_axis_number(axis)
if isinstance(func, np.ufunc):
new_series = {}
... | [
"\n Analogous to DataFrame.apply, for SparseDataFrame\n\n Parameters\n ----------\n func : function\n Function to apply to each column\n axis : {0, 1, 'index', 'columns'}\n broadcast : bool, default False\n For aggregation functions, return object of s... |
Please provide a description of the function:def conda_package_to_pip(package):
if package in EXCLUDE:
return
package = re.sub('(?<=[^<>])=', '==', package).strip()
for compare in ('<=', '>=', '=='):
if compare not in package:
continue
pkg, version = package.split(... | [
"\n Convert a conda package to its pip equivalent.\n\n In most cases they are the same, those are the exceptions:\n - Packages that should be excluded (in `EXCLUDE`)\n - Packages that should be renamed (in `RENAME`)\n - A package requiring a specific version, in conda is defined with a single\n ... |
Please provide a description of the function:def main(conda_fname, pip_fname, compare=False):
with open(conda_fname) as conda_fd:
deps = yaml.safe_load(conda_fd)['dependencies']
pip_deps = []
for dep in deps:
if isinstance(dep, str):
conda_dep = conda_package_to_pip(dep)
... | [
"\n Generate the pip dependencies file from the conda file, or compare that\n they are synchronized (``compare=True``).\n\n Parameters\n ----------\n conda_fname : str\n Path to the conda file with dependencies (e.g. `environment.yml`).\n pip_fname : str\n Path to the pip file with d... |
Please provide a description of the function:def maybe_convert_platform(values):
if isinstance(values, (list, tuple)):
values = construct_1d_object_array_from_listlike(list(values))
if getattr(values, 'dtype', None) == np.object_:
if hasattr(values, '_values'):
values = values.... | [
" try to do platform conversion, allow ndarray or list here "
] |
Please provide a description of the function:def is_nested_object(obj):
if isinstance(obj, ABCSeries) and is_object_dtype(obj):
if any(isinstance(v, ABCSeries) for v in obj.values):
return True
return False | [
"\n return a boolean if we have a nested object, e.g. a Series with 1 or\n more Series elements\n\n This may not be necessarily be performant.\n\n "
] |
Please provide a description of the function:def maybe_downcast_to_dtype(result, dtype):
if is_scalar(result):
return result
def trans(x):
return x
if isinstance(dtype, str):
if dtype == 'infer':
inferred_type = lib.infer_dtype(ensure_object(result.ravel()),
... | [
" try to cast to the specified dtype (e.g. convert back to bool/int\n or could be an astype of float64->float32\n "
] |
Please provide a description of the function:def maybe_upcast_putmask(result, mask, other):
if not isinstance(result, np.ndarray):
raise ValueError("The result input must be a ndarray.")
if mask.any():
# Two conversions for date-like dtypes that can't be done automatically
# in np... | [
"\n A safe version of putmask that potentially upcasts the result.\n The result is replaced with the first N elements of other,\n where N is the number of True values in mask.\n If the length of other is shorter than N, other will be repeated.\n\n Parameters\n ----------\n result : ndarray\n ... |
Please provide a description of the function:def infer_dtype_from(val, pandas_dtype=False):
if is_scalar(val):
return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype)
return infer_dtype_from_array(val, pandas_dtype=pandas_dtype) | [
"\n interpret the dtype from a scalar or array. This is a convenience\n routines to infer dtype from a scalar or an array\n\n Parameters\n ----------\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, scalar/array belongs to panda... |
Please provide a description of the function:def infer_dtype_from_scalar(val, pandas_dtype=False):
dtype = np.object_
# a 1-element ndarray
if isinstance(val, np.ndarray):
msg = "invalid ndarray passed to infer_dtype_from_scalar"
if val.ndim != 0:
raise ValueError(msg)
... | [
"\n interpret the dtype from a scalar\n\n Parameters\n ----------\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, scalar belongs to pandas extension types is inferred as\n object\n "
] |
Please provide a description of the function:def infer_dtype_from_array(arr, pandas_dtype=False):
if isinstance(arr, np.ndarray):
return arr.dtype, arr
if not is_list_like(arr):
arr = [arr]
if pandas_dtype and is_extension_type(arr):
return arr.dtype, arr
elif isinstance... | [
"\n infer the dtype from a scalar or array\n\n Parameters\n ----------\n arr : scalar or array\n pandas_dtype : bool, default False\n whether to infer dtype including pandas extension types.\n If False, array belongs to pandas extension types\n is inferred as object\n\n Return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.