Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def reindex_indexer(self, new_axis, indexer, axis, fill_value=None,
allow_dups=False, copy=True):
if indexer is None:
if new_axis is self.axes[axis] and not copy:
return self
result = self.copy... | [
"\n Parameters\n ----------\n new_axis : Index\n indexer : ndarray of int64 or None\n axis : int\n fill_value : object\n allow_dups : bool\n\n pandas-indexer with -1's only.\n "
] |
Please provide a description of the function:def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None):
allow_fill = fill_tuple is not None
sl_type, slobj, sllen = _preprocess_slice_or_indexer(
slice_or_indexer, self.shape[0], allow_fill=allow_fill)
if self._is_... | [
"\n Slice/take blocks along axis=0.\n\n Overloaded for SingleBlock\n\n Returns\n -------\n new_blocks : list of Block\n\n "
] |
Please provide a description of the function:def take(self, indexer, axis=1, verify=True, convert=True):
self._consolidate_inplace()
indexer = (np.arange(indexer.start, indexer.stop, indexer.step,
dtype='int64')
if isinstance(indexer, slice)
... | [
"\n Take items along any axis.\n "
] |
Please provide a description of the function:def unstack(self, unstacker_func, fill_value):
n_rows = self.shape[-1]
dummy = unstacker_func(np.empty((0, 0)), value_columns=self.items)
new_columns = dummy.get_new_columns()
new_index = dummy.get_new_index()
new_blocks = []
... | [
"Return a blockmanager with all blocks unstacked.\n\n Parameters\n ----------\n unstacker_func : callable\n A (partially-applied) ``pd.core.reshape._Unstacker`` class.\n fill_value : Any\n fill_value for newly introduced missing values.\n\n Returns\n -... |
Please provide a description of the function:def delete(self, item):
loc = self.items.get_loc(item)
self._block.delete(loc)
self.axes[0] = self.axes[0].delete(loc) | [
"\n Delete single item from SingleBlockManager.\n\n Ensures that self.blocks doesn't become empty.\n "
] |
Please provide a description of the function:def concat(self, to_concat, new_axis):
non_empties = [x for x in to_concat if len(x) > 0]
# check if all series are of the same block type:
if len(non_empties) > 0:
blocks = [obj.blocks[0] for obj in non_empties]
if l... | [
"\n Concatenate a list of SingleBlockManagers into a single\n SingleBlockManager.\n\n Used for pd.concat of Series objects with axis=0.\n\n Parameters\n ----------\n to_concat : list of SingleBlockManagers\n new_axis : Index of the result\n\n Returns\n ... |
Please provide a description of the function:def from_array(cls, arr, index=None, name=None, copy=False,
fill_value=None, fastpath=False):
warnings.warn("'from_array' is deprecated and will be removed in a "
"future version. Please use the pd.SparseSeries(..) "
... | [
"Construct SparseSeries from array.\n\n .. deprecated:: 0.23.0\n Use the pd.SparseSeries(..) constructor instead.\n "
] |
Please provide a description of the function:def as_sparse_array(self, kind=None, fill_value=None, copy=False):
if fill_value is None:
fill_value = self.fill_value
if kind is None:
kind = self.kind
return SparseArray(self.values, sparse_index=self.sp_index,
... | [
" return my self as a sparse array, do not copy by default "
] |
Please provide a description of the function:def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
return op(self.get_values(), skipna=skipna, **kwds) | [
" perform a reduction operation "
] |
Please provide a description of the function:def _ixs(self, i, axis=0):
label = self.index[i]
if isinstance(label, Index):
return self.take(i, axis=axis)
else:
return self._get_val_at(i) | [
"\n Return the i-th value or values in the SparseSeries by location\n\n Parameters\n ----------\n i : int, slice, or sequence of integers\n\n Returns\n -------\n value : scalar (int) or Series (slice, sequence)\n "
] |
Please provide a description of the function:def abs(self):
return self._constructor(np.abs(self.values),
index=self.index).__finalize__(self) | [
"\n Return an object with absolute value taken. Only applicable to objects\n that are all numeric\n\n Returns\n -------\n abs: same type as caller\n "
] |
Please provide a description of the function:def get(self, label, default=None):
if label in self.index:
loc = self.index.get_loc(label)
return self._get_val_at(loc)
else:
return default | [
"\n Returns value occupying requested label, default to specified\n missing value if not present. Analogous to dict.get\n\n Parameters\n ----------\n label : object\n Label value looking for\n default : object, optional\n Value to return if label not i... |
Please provide a description of the function:def get_value(self, label, takeable=False):
warnings.warn("get_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
... | [
"\n Retrieve single value at passed index label\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n index : label\n takeable : interpret the index as indexers, default False\n\n Returns\n -------\n v... |
Please provide a description of the function:def set_value(self, label, value, takeable=False):
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
... | [
"\n Quickly set single value at passed label. If label is not contained, a\n new object is created with the label placed at the end of the result\n index\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n label :... |
Please provide a description of the function:def to_dense(self):
return Series(self.values.to_dense(), index=self.index,
name=self.name) | [
"\n Convert SparseSeries to a Series.\n\n Returns\n -------\n s : Series\n "
] |
Please provide a description of the function:def copy(self, deep=True):
# TODO: https://github.com/pandas-dev/pandas/issues/22314
# We skip the block manager till that is resolved.
new_data = self.values.copy(deep=deep)
return self._constructor(new_data, sparse_index=self.sp_ind... | [
"\n Make a copy of the SparseSeries. Only the actual sparse values need to\n be copied\n "
] |
Please provide a description of the function:def sparse_reindex(self, new_index):
if not isinstance(new_index, splib.SparseIndex):
raise TypeError("new index must be a SparseIndex")
values = self.values
values = values.sp_index.to_int_index().reindex(
values.sp_v... | [
"\n Conform sparse values to new SparseIndex\n\n Parameters\n ----------\n new_index : {BlockIndex, IntIndex}\n\n Returns\n -------\n reindexed : SparseSeries\n "
] |
Please provide a description of the function:def cumsum(self, axis=0, *args, **kwargs):
nv.validate_cumsum(args, kwargs)
# Validate axis
if axis is not None:
self._get_axis_number(axis)
new_array = self.values.cumsum()
return self._constructor(
... | [
"\n Cumulative sum of non-NA/null values.\n\n When performing the cumulative summation, any non-NA/null values will\n be skipped. The resulting SparseSeries will preserve the locations of\n NaN values, but the fill value will be `np.nan` regardless.\n\n Parameters\n -------... |
Please provide a description of the function:def dropna(self, axis=0, inplace=False, **kwargs):
# TODO: make more efficient
# Validate axis
self._get_axis_number(axis or 0)
dense_valid = self.to_dense().dropna()
if inplace:
raise NotImplementedError("Cannot p... | [
"\n Analogous to Series.dropna. If fill_value=NaN, returns a dense Series\n "
] |
Please provide a description of the function:def combine_first(self, other):
if isinstance(other, SparseSeries):
other = other.to_dense()
dense_combined = self.to_dense().combine_first(other)
return dense_combined.to_sparse(fill_value=self.fill_value) | [
"\n Combine Series values, choosing the calling Series's values\n first. Result index will be the union of the two indexes\n\n Parameters\n ----------\n other : Series\n\n Returns\n -------\n y : Series\n "
] |
Please provide a description of the function:def _maybe_cache(arg, format, cache, convert_listlike):
from pandas import Series
cache_array = Series()
if cache:
# Perform a quicker unique check
from pandas import Index
unique_dates = Index(arg).unique()
if len(unique_date... | [
"\n Create a cache of unique dates from an array of dates\n\n Parameters\n ----------\n arg : integer, float, string, datetime, list, tuple, 1-d array, Series\n format : string\n Strftime format to parse time\n cache : boolean\n True attempts to create a cache of converted values\n ... |
Please provide a description of the function:def _convert_and_box_cache(arg, cache_array, box, errors, name=None):
from pandas import Series, DatetimeIndex, Index
result = Series(arg).map(cache_array)
if box:
if errors == 'ignore':
return Index(result, name=name)
else:
... | [
"\n Convert array of dates with a cache and box the result\n\n Parameters\n ----------\n arg : integer, float, string, datetime, list, tuple, 1-d array, Series\n cache_array : Series\n Cache of converted, unique dates\n box : boolean\n True boxes result as an Index-like, False return... |
Please provide a description of the function:def _return_parsed_timezone_results(result, timezones, box, tz, name):
if tz is not None:
raise ValueError("Cannot pass a tz argument when "
"parsing strings with timezone "
"information.")
tz_results = n... | [
"\n Return results from array_strptime if a %z or %Z directive was passed.\n\n Parameters\n ----------\n result : ndarray\n int64 date representations of the dates\n timezones : ndarray\n pytz timezone objects\n box : boolean\n True boxes result as an Index-like, False returns... |
Please provide a description of the function:def _convert_listlike_datetimes(arg, box, format, name=None, tz=None,
unit=None, errors=None,
infer_datetime_format=None, dayfirst=None,
yearfirst=None, exact=None):
from... | [
"\n Helper function for to_datetime. Performs the conversions of 1D listlike\n of dates\n\n Parameters\n ----------\n arg : list, tuple, ndarray, Series, Index\n date to be parced\n box : boolean\n True boxes result as an Index-like, False returns an ndarray\n name : object\n ... |
Please provide a description of the function:def _adjust_to_origin(arg, origin, unit):
if origin == 'julian':
original = arg
j0 = Timestamp(0).to_julian_date()
if unit != 'D':
raise ValueError("unit must be 'D' for origin='julian'")
try:
arg = arg - j0
... | [
"\n Helper function for to_datetime.\n Adjust input argument to the specified origin\n\n Parameters\n ----------\n arg : list, tuple, ndarray, Series, Index\n date to be adjusted\n origin : 'julian' or Timestamp\n origin offset for the arg\n unit : string\n passed unit from... |
Please provide a description of the function:def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False,
utc=None, box=True, format=None, exact=True,
unit=None, infer_datetime_format=False, origin='unix',
cache=False):
if arg is None:
return Non... | [
"\n Convert argument to datetime.\n\n Parameters\n ----------\n arg : integer, float, string, datetime, list, tuple, 1-d array, Series\n\n .. versionadded:: 0.18.1\n\n or DataFrame/dict-like\n\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n\n - If 'raise', then inv... |
Please provide a description of the function:def _assemble_from_unit_mappings(arg, errors, box, tz):
from pandas import to_timedelta, to_numeric, DataFrame
arg = DataFrame(arg)
if not arg.columns.is_unique:
raise ValueError("cannot assemble with duplicate keys")
# replace passed unit with ... | [
"\n assemble the unit specified fields from the arg (DataFrame)\n Return a Series for actual parsing\n\n Parameters\n ----------\n arg : DataFrame\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n\n - If 'raise', then invalid parsing will raise an exception\n - If 'coerce',... |
Please provide a description of the function:def _attempt_YYYYMMDD(arg, errors):
def calc(carg):
# calculate the actual result
carg = carg.astype(object)
parsed = parsing.try_parse_year_month_day(carg / 10000,
carg / 100 % 100,
... | [
"\n try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,\n arg is a passed in as an object dtype, but could really be ints/strings\n with nan-like/or floats (e.g. with nan)\n\n Parameters\n ----------\n arg : passed value\n errors : 'raise','ignore','coerce'\n "
] |
Please provide a description of the function:def to_time(arg, format=None, infer_time_format=False, errors='raise'):
def _convert_listlike(arg, format):
if isinstance(arg, (list, tuple)):
arg = np.array(arg, dtype='O')
elif getattr(arg, 'ndim', 1) > 1:
raise TypeError... | [
"\n Parse time strings to time objects using fixed strptime formats (\"%H:%M\",\n \"%H%M\", \"%I:%M%p\", \"%I%M%p\", \"%H:%M:%S\", \"%H%M%S\", \"%I:%M:%S%p\",\n \"%I%M%S%p\")\n\n Use infer_time_format if all the strings are in the same format to speed\n up conversion.\n\n Parameters\n ---------... |
Please provide a description of the function:def deprecate(name, alternative, version, alt_name=None,
klass=None, stacklevel=2, msg=None):
alt_name = alt_name or alternative.__name__
klass = klass or FutureWarning
warning_msg = msg or '{} is deprecated, use {} instead'.format(name,
... | [
"\n Return a new function that emits a deprecation warning on use.\n\n To use this method for a deprecated function, another function\n `alternative` with the same signature must exist. The deprecated\n function will emit a deprecation warning, and in the docstring\n it will contain the deprecation d... |
Please provide a description of the function:def deprecate_kwarg(old_arg_name, new_arg_name, mapping=None, stacklevel=2):
if mapping is not None and not hasattr(mapping, 'get') and \
not callable(mapping):
raise TypeError("mapping from old to new argument values "
"... | [
"\n Decorator to deprecate a keyword argument of a function.\n\n Parameters\n ----------\n old_arg_name : str\n Name of argument in function to deprecate\n new_arg_name : str or None\n Name of preferred argument in function. Use None to raise warning that\n ``old_arg_name`` keywo... |
Please provide a description of the function:def make_signature(func):
spec = inspect.getfullargspec(func)
if spec.defaults is None:
n_wo_defaults = len(spec.args)
defaults = ('',) * n_wo_defaults
else:
n_wo_defaults = len(spec.args) - len(spec.defaults)
defaults = ('',... | [
"\n Returns a tuple containing the paramenter list with defaults\n and parameter list.\n\n Examples\n --------\n >>> def f(a, b, c=2):\n >>> return a * b * c\n >>> print(make_signature(f))\n (['a', 'b', 'c=2'], ['a', 'b', 'c'])\n "
] |
Please provide a description of the function:def period_range(start=None, end=None, periods=None, freq=None, name=None):
if com.count_not_none(start, end, periods) != 2:
raise ValueError('Of the three parameters: start, end, and periods, '
'exactly two must be specified')
i... | [
"\n Return a fixed frequency PeriodIndex, with day (calendar) as the default\n frequency\n\n Parameters\n ----------\n start : string or period-like, default None\n Left bound for generating periods\n end : string or period-like, default None\n Right bound for generating periods\n ... |
Please provide a description of the function:def from_range(cls, data, name=None, dtype=None, **kwargs):
if not isinstance(data, range):
raise TypeError(
'{0}(...) must be called with object coercible to a '
'range, {1} was passed'.format(cls.__name__, repr(d... | [
" Create RangeIndex from a range object. "
] |
Please provide a description of the function:def _format_attrs(self):
attrs = self._get_data_as_items()
if self.name is not None:
attrs.append(('name', ibase.default_pprint(self.name)))
return attrs | [
"\n Return a list of tuples of the (attr, formatted_value)\n "
] |
Please provide a description of the function:def min(self, axis=None, skipna=True):
nv.validate_minmax_axis(axis)
return self._minmax('min') | [
"The minimum value of the RangeIndex"
] |
Please provide a description of the function:def max(self, axis=None, skipna=True):
nv.validate_minmax_axis(axis)
return self._minmax('max') | [
"The maximum value of the RangeIndex"
] |
Please provide a description of the function:def argsort(self, *args, **kwargs):
nv.validate_argsort(args, kwargs)
if self._step > 0:
return np.arange(len(self))
else:
return np.arange(len(self) - 1, -1, -1) | [
"\n Returns the indices that would sort the index and its\n underlying data.\n\n Returns\n -------\n argsorted : numpy array\n\n See Also\n --------\n numpy.ndarray.argsort\n "
] |
Please provide a description of the function:def equals(self, other):
if isinstance(other, RangeIndex):
ls = len(self)
lo = len(other)
return (ls == lo == 0 or
ls == lo == 1 and
self._start == other._start or
... | [
"\n Determines if two Index objects contain the same elements.\n "
] |
Please provide a description of the function:def intersection(self, other, sort=False):
self._validate_sort_keyword(sort)
if self.equals(other):
return self._get_reconciled_name_object(other)
if not isinstance(other, RangeIndex):
return super().intersection(oth... | [
"\n Form the intersection of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default False\n Sort the resulting index if possible\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n ... |
Please provide a description of the function:def _min_fitting_element(self, lower_limit):
no_steps = -(-(lower_limit - self._start) // abs(self._step))
return self._start + abs(self._step) * no_steps | [
"Returns the smallest element greater than or equal to the limit"
] |
Please provide a description of the function:def _max_fitting_element(self, upper_limit):
no_steps = (upper_limit - self._start) // abs(self._step)
return self._start + abs(self._step) * no_steps | [
"Returns the largest element smaller than or equal to the limit"
] |
Please provide a description of the function:def _extended_gcd(self, a, b):
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = b, a
while r:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t,... | [
"\n Extended Euclidean algorithms to solve Bezout's identity:\n a*x + b*y = gcd(x, y)\n Finds one particular solution for x, y: s, t\n Returns: gcd, s, t\n "
] |
Please provide a description of the function:def union(self, other, sort=None):
self._assert_can_do_setop(other)
if len(other) == 0 or self.equals(other) or len(self) == 0:
return super().union(other, sort=sort)
if isinstance(other, RangeIndex) and sort is None:
... | [
"\n Form the union of two Index objects and sorts if possible\n\n Parameters\n ----------\n other : Index or array-like\n\n sort : False or None, default None\n Whether to sort resulting index. ``sort=None`` returns a\n mononotically increasing ``RangeIndex``... |
Please provide a description of the function:def _add_numeric_methods_binary(cls):
def _make_evaluate_binop(op, step=False):
def _evaluate_numeric_binop(self, other):
if isinstance(other, (ABCSeries, ABCDataFrame)):
return NotImplemented
... | [
" add in numeric methods, specialized to RangeIndex ",
"\n Parameters\n ----------\n op : callable that accepts 2 parms\n perform the binary op\n step : callable, optional, default to False\n op to apply to the step parm if not None\n ... |
Please provide a description of the function:def to_numpy(self, dtype=None, copy=False):
result = np.asarray(self._ndarray, dtype=dtype)
if copy and result is self._ndarray:
result = result.copy()
return result | [
"\n Convert the PandasArray to a :class:`numpy.ndarray`.\n\n By default, this requires no coercion or copying of data.\n\n Parameters\n ----------\n dtype : numpy.dtype\n The NumPy dtype to pass to :func:`numpy.asarray`.\n copy : bool, default False\n ... |
Please provide a description of the function:def adjoin(space, *lists, **kwargs):
strlen = kwargs.pop('strlen', len)
justfunc = kwargs.pop('justfunc', justify)
out_lines = []
newLists = []
lengths = [max(map(strlen, x)) + space for x in lists[:-1]]
# not the last one
lengths.append(max... | [
"\n Glues together two sets of strings using the amount of space requested.\n The idea is to prettify.\n\n ----------\n space : int\n number of spaces for padding\n lists : str\n list of str which being joined\n strlen : callable\n function used to calculate the length of each... |
Please provide a description of the function:def justify(texts, max_len, mode='right'):
if mode == 'left':
return [x.ljust(max_len) for x in texts]
elif mode == 'center':
return [x.center(max_len) for x in texts]
else:
return [x.rjust(max_len) for x in texts] | [
"\n Perform ljust, center, rjust against string or list-like\n "
] |
Please provide a description of the function:def _pprint_seq(seq, _nest_lvl=0, max_seq_items=None, **kwds):
if isinstance(seq, set):
fmt = "{{{body}}}"
else:
fmt = "[{body}]" if hasattr(seq, '__setitem__') else "({body})"
if max_seq_items is False:
nitems = len(seq)
else:
... | [
"\n internal. pprinter for iterables. you should probably use pprint_thing()\n rather then calling this directly.\n\n bounds length of printed sequence, depending on options\n "
] |
Please provide a description of the function:def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
fmt = "{{{things}}}"
pairs = []
pfmt = "{key}: {val}"
if max_seq_items is False:
nitems = len(seq)
else:
nitems = max_seq_items or get_option("max_seq_items") or len(se... | [
"\n internal. pprinter for iterables. you should probably use pprint_thing()\n rather then calling this directly.\n "
] |
Please provide a description of the function:def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
quote_strings=False, max_seq_items=None):
def as_escaped_unicode(thing, escape_chars=escape_chars):
# Unicode is fine, else we try to decode using utf-8 and 'rep... | [
"\n This function is the sanctioned way of converting objects\n to a unicode representation.\n\n properly handles nested sequences containing unicode strings\n (unicode(object) does not)\n\n Parameters\n ----------\n thing : anything to be formatted\n _nest_lvl : internal use only. pprint_th... |
Please provide a description of the function:def format_object_summary(obj, formatter, is_justify=True, name=None,
indent_for_name=True):
from pandas.io.formats.console import get_console_size
from pandas.io.formats.format import _get_adjustment
display_width, _ = get_console... | [
"\n Return the formatted obj as a unicode string\n\n Parameters\n ----------\n obj : object\n must be iterable and support __getitem__\n formatter : callable\n string formatter for an element\n is_justify : boolean\n should justify the display\n name : name, optional\n ... |
Please provide a description of the function:def format_object_attrs(obj):
attrs = []
if hasattr(obj, 'dtype'):
attrs.append(('dtype', "'{}'".format(obj.dtype)))
if getattr(obj, 'name', None) is not None:
attrs.append(('name', default_pprint(obj.name)))
max_seq_items = get_option('d... | [
"\n Return a list of tuples of the (attr, formatted_value)\n for common attrs, including dtype, name, length\n\n Parameters\n ----------\n obj : object\n must be iterable\n\n Returns\n -------\n list\n\n "
] |
Please provide a description of the function:def read_gbq(query, project_id=None, index_col=None, col_order=None,
reauth=False, auth_local_webserver=False, dialect=None,
location=None, configuration=None, credentials=None,
use_bqstorage_api=None, private_key=None, verbose=None):
... | [
"\n Load data from Google BigQuery.\n\n This function requires the `pandas-gbq package\n <https://pandas-gbq.readthedocs.io>`__.\n\n See the `How to authenticate with Google BigQuery\n <https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html>`__\n guide for authentication instruction... |
Please provide a description of the function:def scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False,
diagonal='hist', marker='.', density_kwds=None,
hist_kwds=None, range_padding=0.05, **kwds):
df = frame._get_numeric_data()
n = df.columns.size
nax... | [
"\n Draw a matrix of scatter plots.\n\n Parameters\n ----------\n frame : DataFrame\n alpha : float, optional\n amount of transparency applied\n figsize : (float,float), optional\n a tuple (width, height) in inches\n ax : Matplotlib axis object, optional\n grid : bool, optional... |
Please provide a description of the function:def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def normalize(series):
a = min(series)
b = max(series)
return (series - a) / (b - a)
... | [
"\n Plot a multidimensional dataset in 2D.\n\n Each Series in the DataFrame is represented as a evenly distributed\n slice on a circle. Each data point is rendered in the circle according to\n the value on each Series. Highly correlated `Series` in the `DataFrame`\n are placed closer on the unit circ... |
Please provide a description of the function:def andrews_curves(frame, class_column, ax=None, samples=200, color=None,
colormap=None, **kwds):
from math import sqrt, pi
import matplotlib.pyplot as plt
def function(amplitudes):
def f(t):
x1 = amplitudes[0]
... | [
"\n Generate a matplotlib plot of Andrews curves, for visualising clusters of\n multivariate data.\n\n Andrews curves have the functional form:\n\n f(t) = x_1/sqrt(2) + x_2 sin(t) + x_3 cos(t) +\n x_4 sin(2t) + x_5 cos(2t) + ...\n\n Where x coefficients correspond to the values of each dime... |
Please provide a description of the function:def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
import random
import matplotlib.pyplot as plt
# random.sample(ndarray, int) fails on python 3.3, sigh
data = list(series.values)
samplings = [random.sample(data, size) for _ in rang... | [
"\n Bootstrap plot on mean, median and mid-range statistics.\n\n The bootstrap plot is used to estimate the uncertainty of a statistic\n by relaying on random sampling with replacement [1]_. This function will\n generate bootstrapping plots for mean, median and mid-range statistics\n for the given nu... |
Please provide a description of the function:def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
use_columns=False, xticks=None, colormap=None,
axvlines=True, axvlines_kwds=None, sort_labels=False,
**kwds):
if ... | [
"Parallel coordinates plotting.\n\n Parameters\n ----------\n frame : DataFrame\n class_column : str\n Column name containing class names\n cols : list, optional\n A list of column names to use\n ax : matplotlib.axis, optional\n matplotlib axis object\n color : list or tupl... |
Please provide a description of the function:def lag_plot(series, lag=1, ax=None, **kwds):
import matplotlib.pyplot as plt
# workaround because `c='b'` is hardcoded in matplotlibs scatter method
kwds.setdefault('c', plt.rcParams['patch.facecolor'])
data = series.values
y1 = data[:-lag]
y2... | [
"Lag plot for time series.\n\n Parameters\n ----------\n series : Time series\n lag : lag of the scatter plot, default 1\n ax : Matplotlib axis object, optional\n kwds : Matplotlib scatter method keyword arguments, optional\n\n Returns\n -------\n class:`matplotlib.axis.Axes`\n "
] |
Please provide a description of the function:def autocorrelation_plot(series, ax=None, **kwds):
import matplotlib.pyplot as plt
n = len(series)
data = np.asarray(series)
if ax is None:
ax = plt.gca(xlim=(1, n), ylim=(-1.0, 1.0))
mean = np.mean(data)
c0 = np.sum((data - mean) ** 2) /... | [
"\n Autocorrelation plot for time series.\n\n Parameters:\n -----------\n series: Time series\n ax: Matplotlib axis object, optional\n kwds : keywords\n Options to pass to matplotlib plotting method\n\n Returns:\n -----------\n class:`matplotlib.axis.Axes`\n "
] |
Please provide a description of the function:def _any_pandas_objects(terms):
return any(isinstance(term.value, pd.core.generic.PandasObject)
for term in terms) | [
"Check a sequence of terms for instances of PandasObject."
] |
Please provide a description of the function:def _align(terms):
try:
# flatten the parse tree (a nested list, really)
terms = list(com.flatten(terms))
except TypeError:
# can't iterate so it must just be a constant or single variable
if isinstance(terms.value, pd.core.generi... | [
"Align a set of terms"
] |
Please provide a description of the function:def _reconstruct_object(typ, obj, axes, dtype):
try:
typ = typ.type
except AttributeError:
pass
res_t = np.result_type(obj.dtype, dtype)
if (not isinstance(typ, partial) and
issubclass(typ, pd.core.generic.PandasObject)):
... | [
"Reconstruct an object given its type, raw value, and possibly empty\n (None) axes.\n\n Parameters\n ----------\n typ : object\n A type\n obj : object\n The value to use in the type constructor\n axes : dict\n The axes to use to construct the resulting pandas object\n\n Ret... |
Please provide a description of the function:def tsplot(series, plotf, ax=None, **kwargs):
import warnings
warnings.warn("'tsplot' is deprecated and will be removed in a "
"future version. Please use Series.plot() instead.",
FutureWarning, stacklevel=2)
# Used infer... | [
"\n Plots a Series on the given Matplotlib axes or the current axes\n\n Parameters\n ----------\n axes : Axes\n series : Series\n\n Notes\n _____\n Supports same kwargs as Axes.plot\n\n\n .. deprecated:: 0.23.0\n Use Series.plot() instead\n "
] |
Please provide a description of the function:def _decorate_axes(ax, freq, kwargs):
if not hasattr(ax, '_plot_data'):
ax._plot_data = []
ax.freq = freq
xaxis = ax.get_xaxis()
xaxis.freq = freq
if not hasattr(ax, 'legendlabels'):
ax.legendlabels = [kwargs.get('label', None)]
... | [
"Initialize axes for time-series plotting"
] |
Please provide a description of the function:def _get_ax_freq(ax):
ax_freq = getattr(ax, 'freq', None)
if ax_freq is None:
# check for left/right ax in case of secondary yaxis
if hasattr(ax, 'left_ax'):
ax_freq = getattr(ax.left_ax, 'freq', None)
elif hasattr(ax, 'right_... | [
"\n Get the freq attribute of the ax object if set.\n Also checks shared axes (eg when using secondary yaxis, sharex=True\n or twinx)\n "
] |
Please provide a description of the function:def format_timedelta_ticks(x, pos, n_decimals):
s, ns = divmod(x, 1e9)
m, s = divmod(s, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
decimals = int(ns * 10**(n_decimals - 9))
s = r'{:02d}:{:02d}:{:02d}'.format(int(h), int(m), int(s))
if n_de... | [
"\n Convert seconds to 'D days HH:MM:SS.F'\n "
] |
Please provide a description of the function:def format_dateaxis(subplot, freq, index):
# handle index specific formatting
# Note: DatetimeIndex does not use this
# interface. DatetimeIndex uses matplotlib.date directly
if isinstance(index, ABCPeriodIndex):
majlocator = TimeSeries_DateLoc... | [
"\n Pretty-formats the date axis (x-axis).\n\n Major and minor ticks are automatically set for the frequency of the\n current underlying series. As the dynamic mode is activated by\n default, changing the limits of the x axis will intelligently change\n the positions of the ticks.\n "
] |
Please provide a description of the function:def _is_homogeneous_type(self):
if self._data.any_extension_types:
return len({block.dtype for block in self._data.blocks}) == 1
else:
return not self._data.is_mixed_type | [
"\n Whether all the columns in a DataFrame have the same type.\n\n Returns\n -------\n bool\n\n Examples\n --------\n >>> DataFrame({\"A\": [1, 2], \"B\": [3, 4]})._is_homogeneous_type\n True\n >>> DataFrame({\"A\": [1, 2], \"B\": [3.0, 4.0]})._is_homog... |
Please provide a description of the function:def _repr_html_(self):
if self._info_repr():
buf = StringIO("")
self.info(buf=buf)
# need to escape the <class>, should be the first line.
val = buf.getvalue().replace('<', r'<', 1)
val = val.rep... | [
"\n Return a html representation for a particular DataFrame.\n\n Mainly for IPython notebook.\n "
] |
Please provide a description of the function:def to_string(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, justify=None,
max_rows=None, max_cols=None, show_dime... | [
"\n Render a DataFrame to a console-friendly tabular output.\n %(shared_params)s\n line_width : int, optional\n Width to wrap a line in characters.\n %(returns)s\n See Also\n --------\n to_html : Convert DataFrame to HTML.\n\n Examples\n ----... |
Please provide a description of the function:def iteritems(self):
r
if self.columns.is_unique and hasattr(self, '_item_cache'):
for k in self.columns:
yield k, self._get_item_cache(k)
else:
for i, k in enumerate(self.columns):
yield k, self... | [
"\n Iterator over (column name, Series) pairs.\n\n Iterates over the DataFrame columns, returning a tuple with\n the column name and the content as a Series.\n\n Yields\n ------\n label : object\n The column names for the DataFrame being iterated over.\n c... |
Please provide a description of the function:def iterrows(self):
columns = self.columns
klass = self._constructor_sliced
for k, v in zip(self.index, self.values):
s = klass(v, index=columns, name=k)
yield k, s | [
"\n Iterate over DataFrame rows as (index, Series) pairs.\n\n Yields\n ------\n index : label or tuple of label\n The index of the row. A tuple for a `MultiIndex`.\n data : Series\n The data of the row as a Series.\n\n it : generator\n A gen... |
Please provide a description of the function:def itertuples(self, index=True, name="Pandas"):
arrays = []
fields = list(self.columns)
if index:
arrays.append(self.index)
fields.insert(0, "Index")
# use integer indexing because of possible duplicate colum... | [
"\n Iterate over DataFrame rows as namedtuples.\n\n Parameters\n ----------\n index : bool, default True\n If True, return the index as the first element of the tuple.\n name : str or None, default \"Pandas\"\n The name of the returned namedtuples or None to ... |
Please provide a description of the function:def dot(self, other):
if isinstance(other, (Series, DataFrame)):
common = self.columns.union(other.index)
if (len(common) > len(self.columns) or
len(common) > len(other.index)):
raise ValueError('ma... | [
"\n Compute the matrix mutiplication between the DataFrame and other.\n\n This method computes the matrix product between the DataFrame and the\n values of an other Series, DataFrame or a numpy array.\n\n It can also be called using ``self @ other`` in Python >= 3.5.\n\n Parameter... |
Please provide a description of the function:def from_dict(cls, data, orient='columns', dtype=None, columns=None):
index = None
orient = orient.lower()
if orient == 'index':
if len(data) > 0:
# TODO speed up Series case
if isinstance(list(data... | [
"\n Construct DataFrame from dict of array-like or dicts.\n\n Creates DataFrame object from dictionary by columns or by index\n allowing dtype specification.\n\n Parameters\n ----------\n data : dict\n Of the form {field : array-like} or {field : dict}.\n ... |
Please provide a description of the function:def to_numpy(self, dtype=None, copy=False):
result = np.array(self.values, dtype=dtype, copy=copy)
return result | [
"\n Convert the DataFrame to a NumPy array.\n\n .. versionadded:: 0.24.0\n\n By default, the dtype of the returned array will be the common NumPy\n dtype of all types in the DataFrame. For example, if the dtypes are\n ``float16`` and ``float32``, the results dtype will be ``float3... |
Please provide a description of the function:def to_dict(self, orient='dict', into=dict):
if not self.columns.is_unique:
warnings.warn("DataFrame columns are not unique, some "
"columns will be omitted.", UserWarning,
stacklevel=2)
... | [
"\n Convert the DataFrame to a dictionary.\n\n The type of the key-value pairs can be customized with the parameters\n (see below).\n\n Parameters\n ----------\n orient : str {'dict', 'list', 'series', 'split', 'records', 'index'}\n Determines the type of the val... |
Please provide a description of the function:def to_gbq(self, destination_table, project_id=None, chunksize=None,
reauth=False, if_exists='fail', auth_local_webserver=False,
table_schema=None, location=None, progress_bar=True,
credentials=None, verbose=None, private_key=None... | [
"\n Write a DataFrame to a Google BigQuery table.\n\n This function requires the `pandas-gbq package\n <https://pandas-gbq.readthedocs.io>`__.\n\n See the `How to authenticate with Google BigQuery\n <https://pandas-gbq.readthedocs.io/en/latest/howto/authentication.html>`__\n ... |
Please provide a description of the function:def from_records(cls, data, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None):
# Make a copy of the input columns so we can modify it
if columns is not None:
columns = ensure_index(columns)
... | [
"\n Convert structured or record ndarray to DataFrame.\n\n Parameters\n ----------\n data : ndarray (structured dtype), list of tuples, dict, or DataFrame\n index : string, list of fields, array-like\n Field of array to use as the index, alternately a specific set of\n ... |
Please provide a description of the function:def to_records(self, index=True, convert_datetime64=None,
column_dtypes=None, index_dtypes=None):
if convert_datetime64 is not None:
warnings.warn("The 'convert_datetime64' parameter is "
"deprecated ... | [
"\n Convert DataFrame to a NumPy record array.\n\n Index will be included as the first field of the record array if\n requested.\n\n Parameters\n ----------\n index : bool, default True\n Include index in resulting record array, stored in 'index'\n fie... |
Please provide a description of the function:def from_items(cls, items, columns=None, orient='columns'):
warnings.warn("from_items is deprecated. Please use "
"DataFrame.from_dict(dict(items), ...) instead. "
"DataFrame.from_dict(OrderedDict(items)) may be u... | [
"\n Construct a DataFrame from a list of tuples.\n\n .. deprecated:: 0.23.0\n `from_items` is deprecated and will be removed in a future version.\n Use :meth:`DataFrame.from_dict(dict(items)) <DataFrame.from_dict>`\n instead.\n :meth:`DataFrame.from_dict(OrderedDict... |
Please provide a description of the function:def from_csv(cls, path, header=0, sep=',', index_col=0, parse_dates=True,
encoding=None, tupleize_cols=None,
infer_datetime_format=False):
warnings.warn("from_csv is deprecated. Please use read_csv(...) "
... | [
"\n Read CSV file.\n\n .. deprecated:: 0.21.0\n Use :func:`read_csv` instead.\n\n It is preferable to use the more powerful :func:`read_csv`\n for most general purposes, but ``from_csv`` makes for an easy\n roundtrip to and from a file (the exact counterpart of\n ... |
Please provide a description of the function:def to_sparse(self, fill_value=None, kind='block'):
from pandas.core.sparse.api import SparseDataFrame
return SparseDataFrame(self._series, index=self.index,
columns=self.columns, default_kind=kind,
... | [
"\n Convert to SparseDataFrame.\n\n Implement the sparse version of the DataFrame meaning that any data\n matching a specific value it's omitted in the representation.\n The sparse DataFrame allows for a more efficient storage.\n\n Parameters\n ----------\n fill_valu... |
Please provide a description of the function:def to_stata(self, fname, convert_dates=None, write_index=True,
encoding="latin-1", byteorder=None, time_stamp=None,
data_label=None, variable_labels=None, version=114,
convert_strl=None):
kwargs = {}
... | [
"\n Export DataFrame object to Stata dta format.\n\n Writes the DataFrame to a Stata dataset file.\n \"dta\" files contain a Stata dataset.\n\n Parameters\n ----------\n fname : str, buffer or path object\n String, path object (pathlib.Path or py._path.local.Loca... |
Please provide a description of the function:def to_feather(self, fname):
from pandas.io.feather_format import to_feather
to_feather(self, fname) | [
"\n Write out the binary feather-format for DataFrames.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n fname : str\n string file path\n "
] |
Please provide a description of the function:def to_parquet(self, fname, engine='auto', compression='snappy',
index=None, partition_cols=None, **kwargs):
from pandas.io.parquet import to_parquet
to_parquet(self, fname, engine,
compression=compression, index... | [
"\n Write a DataFrame to the binary parquet format.\n\n .. versionadded:: 0.21.0\n\n This function writes the dataframe as a `parquet file\n <https://parquet.apache.org/>`_. You can choose different parquet\n backends, and have the option of compression. See\n :ref:`the use... |
Please provide a description of the function:def to_html(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, justify=None, max_rows=None,
max_cols=None, show_dimensions=F... | [
"\n Render a DataFrame as an HTML table.\n %(shared_params)s\n bold_rows : bool, default True\n Make the row labels bold in the output.\n classes : str or list or tuple, default None\n CSS class(es) to apply to the resulting html table.\n escape : bool, defau... |
Please provide a description of the function:def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None,
null_counts=None):
if buf is None: # pragma: no cover
buf = sys.stdout
lines = []
lines.append(str(type(self)))
lines.append(self.in... | [
"\n Print a concise summary of a DataFrame.\n\n This method prints information about a DataFrame including\n the index dtype and column dtypes, non-null values and memory usage.\n\n Parameters\n ----------\n verbose : bool, optional\n Whether to print the full su... |
Please provide a description of the function:def memory_usage(self, index=True, deep=False):
result = Series([c.memory_usage(index=False, deep=deep)
for col, c in self.iteritems()], index=self.columns)
if index:
result = Series(self.index.memory_usage(deep=d... | [
"\n Return the memory usage of each column in bytes.\n\n The memory usage can optionally include the contribution of\n the index and elements of `object` dtype.\n\n This value is displayed in `DataFrame.info` by default. This can be\n suppressed by setting ``pandas.options.display... |
Please provide a description of the function:def transpose(self, *args, **kwargs):
nv.validate_transpose(args, dict())
return super().transpose(1, 0, **kwargs) | [
"\n Transpose index and columns.\n\n Reflect the DataFrame over its main diagonal by writing rows as columns\n and vice-versa. The property :attr:`.T` is an accessor to the method\n :meth:`transpose`.\n\n Parameters\n ----------\n copy : bool, default False\n ... |
Please provide a description of the function:def get_value(self, index, col, takeable=False):
warnings.warn("get_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
... | [
"\n Quickly retrieve single value at passed column and index.\n\n .. deprecated:: 0.21.0\n Use .at[] or .iat[] accessors instead.\n\n Parameters\n ----------\n index : row label\n col : column label\n takeable : interpret the index/col as indexers, default... |
Please provide a description of the function:def set_value(self, index, col, value, takeable=False):
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
... | [
"\n Put single value at passed column and index.\n\n .. deprecated:: 0.21.0\n Use .at[] or .iat[] accessors instead.\n\n Parameters\n ----------\n index : row label\n col : column label\n value : scalar\n takeable : interpret the index/col as indexe... |
Please provide a description of the function:def _ixs(self, i, axis=0):
# irow
if axis == 0:
if isinstance(i, slice):
return self[i]
else:
label = self.index[i]
if isinstance(label, Index):
# a location ... | [
"\n Parameters\n ----------\n i : int, slice, or sequence of integers\n axis : int\n\n Notes\n -----\n If slice passed, the resulting data will be a view.\n "
] |
Please provide a description of the function:def query(self, expr, inplace=False, **kwargs):
inplace = validate_bool_kwarg(inplace, 'inplace')
if not isinstance(expr, str):
msg = "expr must be a string to be evaluated, {0} given"
raise ValueError(msg.format(type(expr)))
... | [
"\n Query the columns of a DataFrame with a boolean expression.\n\n Parameters\n ----------\n expr : str\n The query string to evaluate. You can refer to variables\n in the environment by prefixing them with an '@' character like\n ``@a + b``.\n\n ... |
Please provide a description of the function:def eval(self, expr, inplace=False, **kwargs):
from pandas.core.computation.eval import eval as _eval
inplace = validate_bool_kwarg(inplace, 'inplace')
resolvers = kwargs.pop('resolvers', None)
kwargs['level'] = kwargs.pop('level', 0... | [
"\n Evaluate a string describing operations on DataFrame columns.\n\n Operates on columns only, not specific rows or elements. This allows\n `eval` to run arbitrary code, which can make you vulnerable to code\n injection if you pass user input to this function.\n\n Parameters\n ... |
Please provide a description of the function:def select_dtypes(self, include=None, exclude=None):
def _get_info_slice(obj, indexer):
if not hasattr(obj, '_info_axis_number'):
msg = 'object of type {typ!r} has no info axis'
raise TypeError(msg.for... | [
"\n Return a subset of the DataFrame's columns based on the column dtypes.\n\n Parameters\n ----------\n include, exclude : scalar or list-like\n A selection of dtypes or strings to be included/excluded. At least\n one of these parameters must be supplied.\n\n ... |
Please provide a description of the function:def _box_col_values(self, values, items):
klass = self._constructor_sliced
return klass(values, index=self.index, name=items, fastpath=True) | [
"\n Provide boxed values for a column.\n "
] |
Please provide a description of the function:def _ensure_valid_index(self, value):
# GH5632, make sure that we are a Series convertible
if not len(self.index) and is_list_like(value):
try:
value = Series(value)
except (ValueError, NotImplementedError, Typ... | [
"\n Ensure that if we don't have an index, that we can create one from the\n passed value.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.