Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _is_label_or_level_reference(self, key, axis=0):
if self.ndim > 2:
raise NotImplementedError(
"_is_label_or_level_reference is not implemented for {type}"
.format(type=type(self)))
return (self._is_le... | [
"\n Test whether a key is a label or level reference for a given axis.\n\n To be considered either a label or a level reference, `key` must be a\n string that:\n - (axis=0): Matches a column label or an index level\n - (axis=1): Matches an index label or a column level\n\n ... |
Please provide a description of the function:def _check_label_or_level_ambiguity(self, key, axis=0):
if self.ndim > 2:
raise NotImplementedError(
"_check_label_or_level_ambiguity is not implemented for {type}"
.format(type=type(self)))
axis = self._g... | [
"\n Check whether `key` is ambiguous.\n\n By ambiguous, we mean that it matches both a level of the input\n `axis` and a label of the other axis.\n\n Parameters\n ----------\n key: str or object\n label or level name\n axis: int, default 0\n Axi... |
Please provide a description of the function:def _get_label_or_level_values(self, key, axis=0):
if self.ndim > 2:
raise NotImplementedError(
"_get_label_or_level_values is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_nu... | [
"\n Return a 1-D array of values associated with `key`, a label or level\n from the given `axis`.\n\n Retrieval logic:\n - (axis=0): Return column values if `key` matches a column label.\n Otherwise return index level values if `key` matches an index\n level.\n ... |
Please provide a description of the function:def _drop_labels_or_levels(self, keys, axis=0):
if self.ndim > 2:
raise NotImplementedError(
"_drop_labels_or_levels is not implemented for {type}"
.format(type=type(self)))
axis = self._get_axis_number(ax... | [
"\n Drop labels and/or levels for the given `axis`.\n\n For each key in `keys`:\n - (axis=0): If key matches a column label then drop the column.\n Otherwise if key matches an index level then drop the level.\n - (axis=1): If key matches an index label then drop the row.\n... |
Please provide a description of the function:def empty(self):
return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS) | [
"\n Indicator whether DataFrame is empty.\n\n True if DataFrame is entirely empty (no items), meaning any of the\n axes are of length 0.\n\n Returns\n -------\n bool\n If DataFrame is empty, return True, if not return False.\n\n See Also\n --------\... |
Please provide a description of the function:def _repr_data_resource_(self):
if config.get_option("display.html.table_schema"):
data = self.head(config.get_option('display.max_rows'))
payload = json.loads(data.to_json(orient='table'),
object_pair... | [
"\n Not a real Jupyter special repr method, but we use the same\n naming convention.\n "
] |
Please provide a description of the function:def to_json(self, path_or_buf=None, orient=None, date_format=None,
double_precision=10, force_ascii=True, date_unit='ms',
default_handler=None, lines=False, compression='infer',
index=True):
from pandas.io imp... | [
"\n Convert the object to a JSON string.\n\n Note NaN's and None will be converted to null and datetime objects\n will be converted to UNIX timestamps.\n\n Parameters\n ----------\n path_or_buf : string or file handle, optional\n File path or object. If not speci... |
Please provide a description of the function:def to_hdf(self, path_or_buf, key, **kwargs):
from pandas.io import pytables
return pytables.to_hdf(path_or_buf, key, self, **kwargs) | [
"\n Write the contained data to an HDF5 file using HDFStore.\n\n Hierarchical Data Format (HDF) is self-describing, allowing an\n application to interpret the structure and contents of a file with\n no outside information. One HDF file can hold a mix of related objects\n which can... |
Please provide a description of the function:def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs):
from pandas.io import packers
return packers.to_msgpack(path_or_buf, self, encoding=encoding,
**kwargs) | [
"\n Serialize object to input file path using msgpack format.\n\n THIS IS AN EXPERIMENTAL LIBRARY and the storage format\n may not be stable until a future release.\n\n Parameters\n ----------\n path : string File path, buffer-like, or None\n if None, return gene... |
Please provide a description of the function:def to_sql(self, name, con, schema=None, if_exists='fail', index=True,
index_label=None, chunksize=None, dtype=None, method=None):
from pandas.io import sql
sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,
... | [
"\n Write records stored in a DataFrame to a SQL database.\n\n Databases supported by SQLAlchemy [1]_ are supported. Tables can be\n newly created, appended to, or overwritten.\n\n Parameters\n ----------\n name : string\n Name of SQL table.\n con : sqlalc... |
Please provide a description of the function:def to_pickle(self, path, compression='infer',
protocol=pickle.HIGHEST_PROTOCOL):
from pandas.io.pickle import to_pickle
return to_pickle(self, path, compression=compression,
protocol=protocol) | [
"\n Pickle (serialize) object to file.\n\n Parameters\n ----------\n path : str\n File path where the pickled object will be stored.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, \\\n default 'infer'\n A string representing the compressi... |
Please provide a description of the function:def to_clipboard(self, excel=True, sep=None, **kwargs):
r
from pandas.io import clipboards
clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs) | [
"\n Copy object to the system clipboard.\n\n Write a text representation of object to the system clipboard.\n This can be pasted into Excel, for example.\n\n Parameters\n ----------\n excel : bool, default True\n - True, use the provided separator, writing in a c... |
Please provide a description of the function:def to_xarray(self):
try:
import xarray
except ImportError:
# Give a nice error message
raise ImportError("the xarray library is not installed\n"
"you can install via conda\n"
... | [
"\n Return an xarray object from the pandas object.\n\n Returns\n -------\n xarray.DataArray or xarray.Dataset\n Data in the pandas structure converted to Dataset if the object is\n a DataFrame, or a DataArray if the object is a Series.\n\n See Also\n ... |
Please provide a description of the function:def to_latex(self, buf=None, columns=None, col_space=None, header=True,
index=True, na_rep='NaN', formatters=None, float_format=None,
sparsify=None, index_names=True, bold_rows=False,
column_format=None, longtable=None, esca... | [
"\n Render an object to a LaTeX tabular environment table.\n\n Render an object to a tabular environment table. You can splice\n this into a LaTeX document. Requires \\usepackage{booktabs}.\n\n .. versionchanged:: 0.20.2\n Added to Series\n\n Parameters\n --------... |
Please provide a description of the function:def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None,
mode='w', encoding=None, compression='infer', quoting=None,
quotechar='"', line_terminator=None, ch... | [
"\n Write object to a comma-separated values (csv) file.\n\n .. versionchanged:: 0.24.0\n The order of arguments for Series was changed.\n\n Parameters\n ----------\n path_or_buf : str or file handle, default None\n File path or object, if None is provided th... |
Please provide a description of the function:def _create_indexer(cls, name, indexer):
if getattr(cls, name, None) is None:
_indexer = functools.partial(indexer, name)
setattr(cls, name, property(_indexer, doc=indexer.__doc__)) | [
"Create an indexer like _name in the class."
] |
Please provide a description of the function:def get(self, key, default=None):
try:
return self[key]
except (KeyError, ValueError, IndexError):
return default | [
"\n Get item from object for given key (DataFrame column, Panel slice,\n etc.). Returns default value if not found.\n\n Parameters\n ----------\n key : object\n\n Returns\n -------\n value : same type as items contained in object\n "
] |
Please provide a description of the function:def _get_item_cache(self, item):
cache = self._item_cache
res = cache.get(item)
if res is None:
values = self._data.get(item)
res = self._box_item_values(item, values)
cache[item] = res
res._set... | [
"Return the cached item, item represents a label indexer."
] |
Please provide a description of the function:def _set_as_cached(self, item, cacher):
self._cacher = (item, weakref.ref(cacher)) | [
"Set the _cacher attribute on the calling object with a weakref to\n cacher.\n "
] |
Please provide a description of the function:def _iget_item_cache(self, item):
ax = self._info_axis
if ax.is_unique:
lower = self._get_item_cache(ax[item])
else:
lower = self._take(item, axis=self._info_axis_number)
return lower | [
"Return the cached item, item represents a positional indexer."
] |
Please provide a description of the function:def _maybe_update_cacher(self, clear=False, verify_is_copy=True):
cacher = getattr(self, '_cacher', None)
if cacher is not None:
ref = cacher[1]()
# we are trying to reference a dead referant, hence
# a copy
... | [
"\n See if we need to update our parent cacher if clear, then clear our\n cache.\n\n Parameters\n ----------\n clear : boolean, default False\n clear the item cache\n verify_is_copy : boolean, default True\n provide is_copy checks\n\n "
] |
Please provide a description of the function:def _slice(self, slobj, axis=0, kind=None):
axis = self._get_block_manager_axis(axis)
result = self._constructor(self._data.get_slice(slobj, axis=axis))
result = result.__finalize__(self)
# this could be a view
# but only in ... | [
"\n Construct a slice of this container.\n\n kind parameter is maintained for compatibility with Series slicing.\n "
] |
Please provide a description of the function:def _check_is_chained_assignment_possible(self):
if self._is_view and self._is_cached:
ref = self._get_cacher()
if ref is not None and ref._is_mixed_type:
self._check_setitem_copy(stacklevel=4, t='referant',
... | [
"\n Check if we are a view, have a cacher, and are of mixed type.\n If so, then force a setitem_copy check.\n\n Should be called just near setting a value\n\n Will return a boolean if it we are a view and are cached, but a\n single-dtype meaning that the cacher should be updated f... |
Please provide a description of the function:def _take(self, indices, axis=0, is_copy=True):
self._consolidate_inplace()
new_data = self._data.take(indices,
axis=self._get_block_manager_axis(axis),
verify=True)
resul... | [
"\n Return the elements in the given *positional* indices along an axis.\n\n This means that we are not indexing according to actual values in\n the index attribute of the object. We are indexing according to the\n actual position of the element in the object.\n\n This is the inte... |
Please provide a description of the function:def take(self, indices, axis=0, convert=None, is_copy=True, **kwargs):
if convert is not None:
msg = ("The 'convert' parameter is deprecated "
"and will be removed in a future version.")
warnings.warn(msg, FutureWar... | [
"\n Return the elements in the given *positional* indices along an axis.\n\n This means that we are not indexing according to actual values in\n the index attribute of the object. We are indexing according to the\n actual position of the element in the object.\n\n Parameters\n ... |
Please provide a description of the function:def xs(self, key, axis=0, level=None, drop_level=True):
axis = self._get_axis_number(axis)
labels = self._get_axis(axis)
if level is not None:
loc, new_ax = labels.get_loc_level(key, level=level,
... | [
"\n Return cross-section from the Series/DataFrame.\n\n This method takes a `key` argument to select data at a particular\n level of a MultiIndex.\n\n Parameters\n ----------\n key : label or tuple of label\n Label contained in the index, or partially in a MultiI... |
Please provide a description of the function:def select(self, crit, axis=0):
warnings.warn("'select' is deprecated and will be removed in a "
"future release. You can use "
".loc[labels.map(crit)] as a replacement",
FutureWarning, stackl... | [
"\n Return data corresponding to axis labels matching criteria.\n\n .. deprecated:: 0.21.0\n Use df.loc[df.index.map(crit)] to select via labels\n\n Parameters\n ----------\n crit : function\n To be called on each index (label). Should return True or False\n ... |
Please provide a description of the function:def reindex_like(self, other, method=None, copy=True, limit=None,
tolerance=None):
d = other._construct_axes_dict(axes=self._AXIS_ORDERS, method=method,
copy=copy, limit=limit,
... | [
"\n Return an object with matching indices as other object.\n\n Conform the object to the same index on all axes. Optional\n filling logic, placing NaN in locations having no value\n in the previous index. A new object is produced unless the\n new index is equivalent to the curren... |
Please provide a description of the function:def _drop_axis(self, labels, axis, level=None, errors='raise'):
axis = self._get_axis_number(axis)
axis_name = self._get_axis_name(axis)
axis = self._get_axis(axis)
if axis.is_unique:
if level is not None:
... | [
"\n Drop labels from specified axis. Used in the ``drop`` method\n internally.\n\n Parameters\n ----------\n labels : single label or list-like\n axis : int or axis name\n level : int or level name, default None\n For MultiIndex\n errors : {'ignore'... |
Please provide a description of the function:def _update_inplace(self, result, verify_is_copy=True):
# NOTE: This does *not* call __finalize__ and that's an explicit
# decision that we may revisit in the future.
self._reset_cache()
self._clear_item_cache()
self._data = ... | [
"\n Replace self internals with result.\n\n Parameters\n ----------\n verify_is_copy : boolean, default True\n provide is_copy checks\n\n "
] |
Please provide a description of the function:def add_prefix(self, prefix):
f = functools.partial('{prefix}{}'.format, prefix=prefix)
mapper = {self._info_axis_name: f}
return self.rename(**mapper) | [
"\n Prefix labels with string `prefix`.\n\n For Series, the row labels are prefixed.\n For DataFrame, the column labels are prefixed.\n\n Parameters\n ----------\n prefix : str\n The string to add before each label.\n\n Returns\n -------\n Se... |
Please provide a description of the function:def add_suffix(self, suffix):
f = functools.partial('{}{suffix}'.format, suffix=suffix)
mapper = {self._info_axis_name: f}
return self.rename(**mapper) | [
"\n Suffix labels with string `suffix`.\n\n For Series, the row labels are suffixed.\n For DataFrame, the column labels are suffixed.\n\n Parameters\n ----------\n suffix : str\n The string to add after each label.\n\n Returns\n -------\n Ser... |
Please provide a description of the function:def sort_values(self, by=None, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
raise NotImplementedError("sort_values has not been implemented "
"on Panel or Panel4D objects.... | [
"\n Sort by the values along either axis.\n\n Parameters\n ----------%(optional_by)s\n axis : %(axes_single_arg)s, default 0\n Axis to be sorted.\n ascending : bool or list of bool, default True\n Sort ascending vs. descending. Specify list for multiple sor... |
Please provide a description of the function:def sort_index(self, axis=0, level=None, ascending=True, inplace=False,
kind='quicksort', na_position='last', sort_remaining=True):
inplace = validate_bool_kwarg(inplace, 'inplace')
axis = self._get_axis_number(axis)
axis_n... | [
"\n Sort object by labels (along an axis).\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n The axis along which to sort. The value 0 identifies the rows,\n and 1 identifies the columns.\n level : int or level name or list of ... |
Please provide a description of the function:def reindex(self, *args, **kwargs):
# TODO: Decide if we care about having different examples for different
# kinds
# construct the args
axes, kwargs = self._construct_axes_from_arguments(args, kwargs)
method = missing.clean_... | [
"\n Conform %(klass)s to new index with optional filling logic, placing\n NA/NaN in locations having no value in the previous index. A new object\n is produced unless the new index is equivalent to the current one and\n ``copy=False``.\n\n Parameters\n ----------\n %... |
Please provide a description of the function:def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,
copy):
obj = self
for a in self._AXIS_ORDERS:
labels = axes[a]
if labels is None:
continue
ax = self... | [
"Perform the reindex for all the axes."
] |
Please provide a description of the function:def _needs_reindex_multi(self, axes, method, level):
return ((com.count_not_none(*axes.values()) == self._AXIS_LEN) and
method is None and level is None and not self._is_mixed_type) | [
"Check if we do need a multi reindex."
] |
Please provide a description of the function:def _reindex_with_indexers(self, reindexers, fill_value=None, copy=False,
allow_dups=False):
# reindex doing multiple operations on different axes if indicated
new_data = self._data
for axis in sorted(reindexer... | [
"allow_dups indicates an internal call here "
] |
Please provide a description of the function:def filter(self, items=None, like=None, regex=None, axis=None):
import re
nkw = com.count_not_none(items, like, regex)
if nkw > 1:
raise TypeError('Keyword arguments `items`, `like`, or `regex` '
'are ... | [
"\n Subset rows or columns of dataframe according to labels in\n the specified index.\n\n Note that this routine does not filter a dataframe on its\n contents. The filter is applied to the labels of the index.\n\n Parameters\n ----------\n items : list-like\n ... |
Please provide a description of the function:def sample(self, n=None, frac=None, replace=False, weights=None,
random_state=None, axis=None):
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)
axis_length = self.shape[axis]
... | [
"\n Return a random sample of items from an axis of object.\n\n You can use `random_state` for reproducibility.\n\n Parameters\n ----------\n n : int, optional\n Number of items from axis to return. Cannot be used with `frac`.\n Default = 1 if `frac` = None.\... |
Please provide a description of the function:def _dir_additions(self):
additions = {c for c in self._info_axis.unique(level=0)[:100]
if isinstance(c, str) and c.isidentifier()}
return super()._dir_additions().union(additions) | [
" add the string-like attributes from the info_axis.\n If info_axis is a MultiIndex, it's first level values are used.\n "
] |
Please provide a description of the function:def _protect_consolidate(self, f):
blocks_before = len(self._data.blocks)
result = f()
if len(self._data.blocks) != blocks_before:
self._clear_item_cache()
return result | [
"Consolidate _data -- if the blocks have changed, then clear the\n cache\n "
] |
Please provide a description of the function:def _consolidate_inplace(self):
def f():
self._data = self._data.consolidate()
self._protect_consolidate(f) | [
"Consolidate data in place and return None"
] |
Please provide a description of the function:def _consolidate(self, inplace=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
if inplace:
self._consolidate_inplace()
else:
f = lambda: self._data.consolidate()
cons_data = self._protect_consolid... | [
"\n Compute NDFrame with \"consolidated\" internals (data of each dtype\n grouped together in a single ndarray).\n\n Parameters\n ----------\n inplace : boolean, default False\n If False return new object, otherwise modify existing object\n\n Returns\n ---... |
Please provide a description of the function:def _check_inplace_setting(self, value):
if self._is_mixed_type:
if not self._is_numeric_mixed_type:
# allow an actual np.nan thru
try:
if np.isnan(value):
return True
... | [
" check whether we allow in-place setting with this type of value "
] |
Please provide a description of the function:def as_matrix(self, columns=None):
warnings.warn("Method .as_matrix will be removed in a future version. "
"Use .values instead.", FutureWarning, stacklevel=2)
self._consolidate_inplace()
return self._data.as_array(trans... | [
"\n Convert the frame to its Numpy-array representation.\n\n .. deprecated:: 0.23.0\n Use :meth:`DataFrame.values` instead.\n\n Parameters\n ----------\n columns : list, optional, default:None\n If None, return all columns, otherwise, returns specified column... |
Please provide a description of the function:def values(self):
self._consolidate_inplace()
return self._data.as_array(transpose=self._AXIS_REVERSED) | [
"\n Return a Numpy representation of the DataFrame.\n\n .. warning::\n\n We recommend using :meth:`DataFrame.to_numpy` instead.\n\n Only the values in the DataFrame will be returned, the axes labels\n will be removed.\n\n Returns\n -------\n numpy.ndarray\n... |
Please provide a description of the function:def get_ftype_counts(self):
warnings.warn("get_ftype_counts is deprecated and will "
"be removed in a future version",
FutureWarning, stacklevel=2)
from pandas import Series
return Series(self._dat... | [
"\n Return counts of unique ftypes in this object.\n\n .. deprecated:: 0.23.0\n\n This is useful for SparseDataFrame or for DataFrames containing\n sparse arrays.\n\n Returns\n -------\n dtype : Series\n Series with the count of columns with each type and\... |
Please provide a description of the function:def dtypes(self):
from pandas import Series
return Series(self._data.get_dtypes(), index=self._info_axis,
dtype=np.object_) | [
"\n Return the dtypes in the DataFrame.\n\n This returns a Series with the data type of each column.\n The result's index is the original DataFrame's columns. Columns\n with mixed types are stored with the ``object`` dtype. See\n :ref:`the User Guide <basics.dtypes>` for more.\n\n... |
Please provide a description of the function:def ftypes(self):
from pandas import Series
return Series(self._data.get_ftypes(), index=self._info_axis,
dtype=np.object_) | [
"\n Return the ftypes (indication of sparse/dense and dtype) in DataFrame.\n\n This returns a Series with the data type of each column.\n The result's index is the original DataFrame's columns. Columns\n with mixed types are stored with the ``object`` dtype. See\n :ref:`the User ... |
Please provide a description of the function:def as_blocks(self, copy=True):
warnings.warn("as_blocks is deprecated and will "
"be removed in a future version",
FutureWarning, stacklevel=2)
return self._to_dict_of_blocks(copy=copy) | [
"\n Convert the frame to a dict of dtype -> Constructor Types that each has\n a homogeneous dtype.\n\n .. deprecated:: 0.21.0\n\n NOTE: the dtypes of the blocks WILL BE PRESERVED HERE (unlike in\n as_matrix)\n\n Parameters\n ----------\n copy : boolean, ... |
Please provide a description of the function:def _to_dict_of_blocks(self, copy=True):
return {k: self._constructor(v).__finalize__(self)
for k, v, in self._data.to_dict(copy=copy).items()} | [
"\n Return a dict of dtype -> Constructor Types that\n each is a homogeneous dtype.\n\n Internal ONLY\n "
] |
Please provide a description of the function:def astype(self, dtype, copy=True, errors='raise', **kwargs):
if is_dict_like(dtype):
if self.ndim == 1: # i.e. Series
if len(dtype) > 1 or self.name not in dtype:
raise KeyError('Only the Series name can be u... | [
"\n Cast a pandas object to a specified dtype ``dtype``.\n\n Parameters\n ----------\n dtype : data type, or dict of column name -> data type\n Use a numpy.dtype or Python type to cast entire pandas object to\n the same type. Alternatively, use {col: dtype, ...}, wh... |
Please provide a description of the function:def copy(self, deep=True):
data = self._data.copy(deep=deep)
return self._constructor(data).__finalize__(self) | [
"\n Make a copy of this object's indices and data.\n\n When ``deep=True`` (default), a new object will be created with a\n copy of the calling object's data and indices. Modifications to\n the data or indices of the copy will not be reflected in the\n original object (see notes be... |
Please provide a description of the function:def _convert(self, datetime=False, numeric=False, timedelta=False,
coerce=False, copy=True):
return self._constructor(
self._data.convert(datetime=datetime, numeric=numeric,
timedelta=timedelta, coe... | [
"\n Attempt to infer better dtype for object columns\n\n Parameters\n ----------\n datetime : boolean, default False\n If True, convert to date where possible.\n numeric : boolean, default False\n If True, attempt to convert to numbers (including strings), wi... |
Please provide a description of the function:def convert_objects(self, convert_dates=True, convert_numeric=False,
convert_timedeltas=True, copy=True):
msg = ("convert_objects is deprecated. To re-infer data dtypes for "
"object columns, use {klass}.infer_objects(... | [
"\n Attempt to infer better dtype for object columns.\n\n .. deprecated:: 0.21.0\n\n Parameters\n ----------\n convert_dates : boolean, default True\n If True, convert to date where possible. If 'coerce', force\n conversion, with unconvertible values becoming... |
Please provide a description of the function:def infer_objects(self):
# numeric=False necessary to only soft convert;
# python objects will still be converted to
# native numpy numeric types
return self._constructor(
self._data.convert(datetime=True, numeric=False,
... | [
"\n Attempt to infer better dtypes for object columns.\n\n Attempts soft conversion of object-dtyped\n columns, leaving non-object and unconvertible\n columns unchanged. The inference rules are the\n same as during normal Series/DataFrame construction.\n\n .. versionadded::... |
Please provide a description of the function:def fillna(self, value=None, method=None, axis=None, inplace=False,
limit=None, downcast=None):
inplace = validate_bool_kwarg(inplace, 'inplace')
value, method = validate_fillna_kwargs(value, method)
self._consolidate_inplace(... | [
"\n Fill NA/NaN values using the specified method.\n\n Parameters\n ----------\n value : scalar, dict, Series, or DataFrame\n Value to use to fill holes (e.g. 0), alternately a\n dict/Series/DataFrame of values specifying which value to use for\n each ind... |
Please provide a description of the function:def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
limit_direction='forward', limit_area=None,
downcast=None, **kwargs):
inplace = validate_bool_kwarg(inplace, 'inplace')
if self.ndim > ... | [
"\n Interpolate values according to different methods.\n "
] |
Please provide a description of the function:def asof(self, where, subset=None):
if isinstance(where, str):
from pandas import to_datetime
where = to_datetime(where)
if not self.index.is_monotonic:
raise ValueError("asof requires a sorted index")
is... | [
"\n Return the last row(s) without any NaNs before `where`.\n\n The last row (for each element in `where`, if list) without any\n NaN is taken.\n In case of a :class:`~pandas.DataFrame`, the last row without NaN\n considering only the subset of columns (if not `None`)\n\n .... |
Please provide a description of the function:def clip(self, lower=None, upper=None, axis=None, inplace=False,
*args, **kwargs):
if isinstance(self, ABCPanel):
raise NotImplementedError("clip is not supported yet for panels")
inplace = validate_bool_kwarg(inplace, 'inpl... | [
"\n Trim values at input threshold(s).\n\n Assigns values outside boundary to boundary values. Thresholds\n can be singular values or array like, and in the latter case\n the clipping is performed element-wise in the specified axis.\n\n Parameters\n ----------\n lowe... |
Please provide a description of the function:def clip_upper(self, threshold, axis=None, inplace=False):
warnings.warn('clip_upper(threshold) is deprecated, '
'use clip(upper=threshold) instead',
FutureWarning, stacklevel=2)
return self._clip_with_one_... | [
"\n Trim values above a given threshold.\n\n .. deprecated:: 0.24.0\n Use clip(upper=threshold) instead.\n\n Elements above the `threshold` will be changed to match the\n `threshold` value(s). Threshold can be a single value or an array,\n in the latter case it performs... |
Please provide a description of the function:def clip_lower(self, threshold, axis=None, inplace=False):
warnings.warn('clip_lower(threshold) is deprecated, '
'use clip(lower=threshold) instead',
FutureWarning, stacklevel=2)
return self._clip_with_one_... | [
"\n Trim values below a given threshold.\n\n .. deprecated:: 0.24.0\n Use clip(lower=threshold) instead.\n\n Elements below the `threshold` will be changed to match the\n `threshold` value(s). Threshold can be a single value or an array,\n in the latter case it performs... |
Please provide a description of the function:def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False, observed=False, **kwargs):
from pandas.core.groupby.groupby import groupby
if level is None and by is None:
raise Ty... | [
"\n Group DataFrame or Series using a mapper or by a Series of columns.\n\n A groupby operation involves some combination of splitting the\n object, applying a function, and combining the results. This can be\n used to group large amounts of data and compute operations on these\n ... |
Please provide a description of the function:def asfreq(self, freq, method=None, how=None, normalize=False,
fill_value=None):
from pandas.core.resample import asfreq
return asfreq(self, freq, method=method, how=how, normalize=normalize,
fill_value=fill_value... | [
"\n Convert TimeSeries to specified frequency.\n\n Optionally provide filling method to pad/backfill missing values.\n\n Returns the original data conformed to a new index with the specified\n frequency. ``resample`` is more appropriate if an operation, such as\n summarization, is... |
Please provide a description of the function:def at_time(self, time, asof=False, axis=None):
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)
index = self._get_axis(axis)
try:
indexer = index.indexer_at_time(time, asof=as... | [
"\n Select values at particular time of day (e.g. 9:30AM).\n\n Parameters\n ----------\n time : datetime.time or str\n axis : {0 or 'index', 1 or 'columns'}, default 0\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n Series or DataFrame\n\n ... |
Please provide a description of the function:def between_time(self, start_time, end_time, include_start=True,
include_end=True, axis=None):
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)
index = self._get_axis(axis)
... | [
"\n Select values between particular times of the day (e.g., 9:00-9:30 AM).\n\n By setting ``start_time`` to be later than ``end_time``,\n you can get the times that are *not* between the two times.\n\n Parameters\n ----------\n start_time : datetime.time or str\n en... |
Please provide a description of the function:def resample(self, rule, how=None, axis=0, fill_method=None, closed=None,
label=None, convention='start', kind=None, loffset=None,
limit=None, base=0, on=None, level=None):
from pandas.core.resample import (resample,
... | [
"\n Resample time-series data.\n\n Convenience method for frequency conversion and resampling of time\n series. Object must have a datetime-like index (`DatetimeIndex`,\n `PeriodIndex`, or `TimedeltaIndex`), or pass datetime-like values\n to the `on` or `level` keyword.\n\n ... |
Please provide a description of the function:def first(self, offset):
if not isinstance(self.index, DatetimeIndex):
raise TypeError("'first' only supports a DatetimeIndex index")
if len(self.index) == 0:
return self
offset = to_offset(offset)
end_date =... | [
"\n Convenience method for subsetting initial periods of time series data\n based on a date offset.\n\n Parameters\n ----------\n offset : string, DateOffset, dateutil.relativedelta\n\n Returns\n -------\n subset : same type as caller\n\n Raises\n ... |
Please provide a description of the function:def last(self, offset):
if not isinstance(self.index, DatetimeIndex):
raise TypeError("'last' only supports a DatetimeIndex index")
if len(self.index) == 0:
return self
offset = to_offset(offset)
start_date ... | [
"\n Convenience method for subsetting final periods of time series data\n based on a date offset.\n\n Parameters\n ----------\n offset : string, DateOffset, dateutil.relativedelta\n\n Returns\n -------\n subset : same type as caller\n\n Raises\n ... |
Please provide a description of the function:def rank(self, axis=0, method='average', numeric_only=None,
na_option='keep', ascending=True, pct=False):
axis = self._get_axis_number(axis)
if self.ndim > 2:
msg = "rank does not make sense when ndim > 2"
raise ... | [
"\n Compute numerical data ranks (1 through n) along axis. Equal values are\n assigned a rank that is the average of the ranks of those values.\n\n Parameters\n ----------\n axis : {0 or 'index', 1 or 'columns'}, default 0\n index to direct ranking\n method : {'a... |
Please provide a description of the function:def _where(self, cond, other=np.nan, inplace=False, axis=None, level=None,
errors='raise', try_cast=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
# align the cond to same shape as myself
cond = com.apply_if_callabl... | [
"\n Equivalent to public method `where`, except that `other` is not\n applied as a function even if callable. Used in __setitem__.\n "
] |
Please provide a description of the function:def slice_shift(self, periods=1, axis=0):
if periods == 0:
return self
if periods > 0:
vslicer = slice(None, -periods)
islicer = slice(periods, None)
else:
vslicer = slice(-periods, None)
... | [
"\n Equivalent to `shift` without copying data. The shifted data will\n not include the dropped periods and the shifted axis will be smaller\n than the original.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\... |
Please provide a description of the function:def tshift(self, periods=1, freq=None, axis=0):
index = self._get_axis(axis)
if freq is None:
freq = getattr(index, 'freq', None)
if freq is None:
freq = getattr(index, 'inferred_freq', None)
if freq is None... | [
"\n Shift the time index, using the index's frequency if available.\n\n Parameters\n ----------\n periods : int\n Number of periods to move, can be positive or negative\n freq : DateOffset, timedelta, or time rule string, default None\n Increment to use from ... |
Please provide a description of the function:def truncate(self, before=None, after=None, axis=None, copy=True):
if axis is None:
axis = self._stat_axis_number
axis = self._get_axis_number(axis)
ax = self._get_axis(axis)
# GH 17935
# Check that index is sort... | [
"\n Truncate a Series or DataFrame before and after some index value.\n\n This is a useful shorthand for boolean indexing based on index\n values above or below certain thresholds.\n\n Parameters\n ----------\n before : date, string, int\n Truncate all rows befor... |
Please provide a description of the function:def tz_convert(self, tz, axis=0, level=None, copy=True):
axis = self._get_axis_number(axis)
ax = self._get_axis(axis)
def _tz_convert(ax, tz):
if not hasattr(ax, 'tz_convert'):
if len(ax) > 0:
... | [
"\n Convert tz-aware axis to target time zone.\n\n Parameters\n ----------\n tz : string or pytz.timezone object\n axis : the axis to convert\n level : int, str, default None\n If axis ia a MultiIndex, convert a specific level. Otherwise\n must be None... |
Please provide a description of the function:def tz_localize(self, tz, axis=0, level=None, copy=True,
ambiguous='raise', nonexistent='raise'):
nonexistent_options = ('raise', 'NaT', 'shift_forward',
'shift_backward')
if nonexistent not in nonex... | [
"\n Localize tz-naive index of a Series or DataFrame to target time zone.\n\n This operation localizes the Index. To localize the values in a\n timezone-naive Series, use :meth:`Series.dt.tz_localize`.\n\n Parameters\n ----------\n tz : string or pytz.timezone object\n ... |
Please provide a description of the function:def describe(self, percentiles=None, include=None, exclude=None):
if self.ndim >= 3:
msg = "describe is not implemented on Panel objects."
raise NotImplementedError(msg)
elif self.ndim == 2 and self.columns.size == 0:
... | [
"\n Generate descriptive statistics that summarize the central tendency,\n dispersion and shape of a dataset's distribution, excluding\n ``NaN`` values.\n\n Analyzes both numeric and object series, as well\n as ``DataFrame`` column sets of mixed data types. The output\n wil... |
Please provide a description of the function:def _check_percentile(self, q):
msg = ("percentiles should all be in the interval [0, 1]. "
"Try {0} instead.")
q = np.asarray(q)
if q.ndim == 0:
if not 0 <= q <= 1:
raise ValueError(msg.format(q / ... | [
"\n Validate percentiles (used by describe and quantile).\n "
] |
Please provide a description of the function:def _add_numeric_operations(cls):
axis_descr, name, name2 = _doc_parms(cls)
cls.any = _make_logical_function(
cls, 'any', name, name2, axis_descr, _any_desc, nanops.nanany,
_any_see_also, _any_examples, empty_value=False)
... | [
"\n Add the operations to the cls; evaluate the doc strings again\n ",
"Return the sum of the values for the requested axis.\\n\n This is equivalent to the method ``numpy.sum``.",
"Return the maximum of the values for the requested axis.\\n\n If you want the *index* of the ma... |
Please provide a description of the function:def _add_series_only_operations(cls):
axis_descr, name, name2 = _doc_parms(cls)
def nanptp(values, axis=0, skipna=True):
nmax = nanops.nanmax(values, axis, skipna)
nmin = nanops.nanmin(values, axis, skipna)
warni... | [
"\n Add the series only operations to the cls; evaluate the doc\n strings again.\n ",
"Return the difference between the maximum value and the\n minimum value in the object. This is the equivalent of the\n ``numpy.ndarray`` method ``ptp``.\\n\\n.. deprecated:: 0.24.0\n ... |
Please provide a description of the function:def _add_series_or_dataframe_operations(cls):
from pandas.core import window as rwindow
@Appender(rwindow.rolling.__doc__)
def rolling(self, window, min_periods=None, center=False,
win_type=None, on=None, axis=0, closed=... | [
"\n Add the series or dataframe only operations to the cls; evaluate\n the doc strings again.\n "
] |
Please provide a description of the function:def _find_valid_index(self, how):
assert how in ['first', 'last']
if len(self) == 0: # early stop
return None
is_valid = ~self.isna()
if self.ndim == 2:
is_valid = is_valid.any(1) # reduce axis 1
i... | [
"\n Retrieves the index of the first valid value.\n\n Parameters\n ----------\n how : {'first', 'last'}\n Use this parameter to change between the first or last valid index.\n\n Returns\n -------\n idx_first_valid : type of index\n "
] |
Please provide a description of the function:def _reset_cache(self, key=None):
if getattr(self, '_cache', None) is None:
return
if key is None:
self._cache.clear()
else:
self._cache.pop(key, None) | [
"\n Reset cached properties. If ``key`` is passed, only clears that key.\n "
] |
Please provide a description of the function:def _try_aggregate_string_function(self, arg, *args, **kwargs):
assert isinstance(arg, str)
f = getattr(self, arg, None)
if f is not None:
if callable(f):
return f(*args, **kwargs)
# people may try to... | [
"\n if arg is a string, then try to operate on it:\n - try to find a function (or attribute) on ourselves\n - try to find a numpy function\n - raise\n\n "
] |
Please provide a description of the function:def _aggregate(self, arg, *args, **kwargs):
is_aggregator = lambda x: isinstance(x, (list, tuple, dict))
is_nested_renamer = False
_axis = kwargs.pop('_axis', None)
if _axis is None:
_axis = getattr(self, 'axis', 0)
... | [
"\n provide an implementation for the aggregators\n\n Parameters\n ----------\n arg : string, dict, function\n *args : args to pass on to the function\n **kwargs : kwargs to pass on to the function\n\n Returns\n -------\n tuple of result, how\n\n ... |
Please provide a description of the function:def _shallow_copy(self, obj=None, obj_type=None, **kwargs):
if obj is None:
obj = self._selected_obj.copy()
if obj_type is None:
obj_type = self._constructor
if isinstance(obj, obj_type):
obj = obj.obj
... | [
"\n return a new object with the replacement attributes\n "
] |
Please provide a description of the function:def itemsize(self):
warnings.warn("{obj}.itemsize is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self._ndarray_values.itemsize | [
"\n Return the size of the dtype of the item of the underlying data.\n\n .. deprecated:: 0.23.0\n "
] |
Please provide a description of the function:def base(self):
warnings.warn("{obj}.base is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self.values.base | [
"\n Return the base object if the memory of the underlying data is shared.\n\n .. deprecated:: 0.23.0\n "
] |
Please provide a description of the function:def array(self) -> ExtensionArray:
result = self._values
if is_datetime64_ns_dtype(result.dtype):
from pandas.arrays import DatetimeArray
result = DatetimeArray(result)
elif is_timedelta64_ns_dtype(result.dtype):
... | [
"\n The ExtensionArray of the data backing this Series or Index.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n ExtensionArray\n An ExtensionArray of the values stored within. For extension\n types, this is the actual array. For NumPy native types, this... |
Please provide a description of the function:def to_numpy(self, dtype=None, copy=False):
if is_datetime64tz_dtype(self.dtype) and dtype is None:
# note: this is going to change very soon.
# I have a WIP PR making this unnecessary, but it's
# a bit out of scope for th... | [
"\n A NumPy ndarray representing the values in this Series or Index.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n dtype : str or numpy.dtype, optional\n The dtype to pass to :meth:`numpy.asarray`\n copy : bool, default False\n Whether to ... |
Please provide a description of the function:def _ndarray_values(self) -> np.ndarray:
if is_extension_array_dtype(self):
return self.array._ndarray_values
return self.values | [
"\n The data as an ndarray, possibly losing information.\n\n The expectation is that this is cheap to compute, and is primarily\n used for interacting with our indexers.\n\n - categorical -> codes\n "
] |
Please provide a description of the function:def max(self, axis=None, skipna=True):
nv.validate_minmax_axis(axis)
return nanops.nanmax(self._values, skipna=skipna) | [
"\n Return the maximum value of the Index.\n\n Parameters\n ----------\n axis : int, optional\n For compatibility with NumPy. Only 0 or None are allowed.\n skipna : bool, default True\n\n Returns\n -------\n scalar\n Maximum value.\n\n ... |
Please provide a description of the function:def argmax(self, axis=None, skipna=True):
nv.validate_minmax_axis(axis)
return nanops.nanargmax(self._values, skipna=skipna) | [
"\n Return an ndarray of the maximum argument indexer.\n\n Parameters\n ----------\n axis : {None}\n Dummy argument for consistency with Series\n skipna : bool, default True\n\n See Also\n --------\n numpy.ndarray.argmax\n "
] |
Please provide a description of the function:def min(self, axis=None, skipna=True):
nv.validate_minmax_axis(axis)
return nanops.nanmin(self._values, skipna=skipna) | [
"\n Return the minimum value of the Index.\n\n Parameters\n ----------\n axis : {None}\n Dummy argument for consistency with Series\n skipna : bool, default True\n\n Returns\n -------\n scalar\n Minimum value.\n\n See Also\n ... |
Please provide a description of the function:def argmin(self, axis=None, skipna=True):
nv.validate_minmax_axis(axis)
return nanops.nanargmin(self._values, skipna=skipna) | [
"\n Return a ndarray of the minimum argument indexer.\n\n Parameters\n ----------\n axis : {None}\n Dummy argument for consistency with Series\n skipna : bool, default True\n\n Returns\n -------\n numpy.ndarray\n\n See Also\n --------\... |
Please provide a description of the function:def tolist(self):
if is_datetimelike(self._values):
return [com.maybe_box_datetimelike(x) for x in self._values]
elif is_extension_array_dtype(self._values):
return list(self._values)
else:
return self._val... | [
"\n Return a list of the values.\n\n These are each a scalar type, which is a Python scalar\n (for str, int, float) or a pandas scalar\n (for Timestamp/Timedelta/Interval/Period)\n\n Returns\n -------\n list\n\n See Also\n --------\n numpy.ndarra... |
Please provide a description of the function:def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
func = getattr(self, name, None)
if func is None:
raise TypeError("{klass} cannot perform the operation {op}".format(
... | [
" perform the reduction type operation if we can "
] |
Please provide a description of the function:def _map_values(self, mapper, na_action=None):
# we can fastpath dict/Series to an efficient map
# as we know that we are not going to have to yield
# python types
if isinstance(mapper, dict):
if hasattr(mapper, '__missin... | [
"\n An internal function that maps values using the input\n correspondence (which can be a dict, Series, or function).\n\n Parameters\n ----------\n mapper : function, dict, or Series\n The input correspondence object\n na_action : {None, 'ignore'}\n I... |
Please provide a description of the function:def value_counts(self, normalize=False, sort=True, ascending=False,
bins=None, dropna=True):
from pandas.core.algorithms import value_counts
result = value_counts(self, sort=sort, ascending=ascending,
... | [
"\n Return a Series containing counts of unique values.\n\n The resulting object will be in descending order so that the\n first element is the most frequently-occurring element.\n Excludes NA values by default.\n\n Parameters\n ----------\n normalize : boolean, defa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.