Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def head(self, n=5):
self._reset_group_selection()
mask = self._cumcount_array() < n
return self._selected_obj[mask] | [
"\n Return first n rows of each group.\n\n Essentially equivalent to ``.apply(lambda x: x.head(n))``,\n except ignores as_index flag.\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]],\n columns=['A',... |
Please provide a description of the function:def tail(self, n=5):
self._reset_group_selection()
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask] | [
"\n Return last n rows of each group.\n\n Essentially equivalent to ``.apply(lambda x: x.tail(n))``,\n except ignores as_index flag.\n %(see_also)s\n Examples\n --------\n\n >>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],\n ... |
Please provide a description of the function:def next_monday(dt):
if dt.weekday() == 5:
return dt + timedelta(2)
elif dt.weekday() == 6:
return dt + timedelta(1)
return dt | [
"\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday, use Monday instead\n "
] |
Please provide a description of the function:def next_monday_or_tuesday(dt):
dow = dt.weekday()
if dow == 5 or dow == 6:
return dt + timedelta(2)
elif dow == 0:
return dt + timedelta(1)
return dt | [
"\n For second holiday of two adjacent ones!\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday or Monday, use following Tuesday instead\n (because Monday is already taken by adjacent holiday on the day before)\n "
] |
Please provide a description of the function:def previous_friday(dt):
if dt.weekday() == 5:
return dt - timedelta(1)
elif dt.weekday() == 6:
return dt - timedelta(2)
return dt | [
"\n If holiday falls on Saturday or Sunday, use previous Friday instead.\n "
] |
Please provide a description of the function:def weekend_to_monday(dt):
if dt.weekday() == 6:
return dt + timedelta(1)
elif dt.weekday() == 5:
return dt + timedelta(2)
return dt | [
"\n If holiday falls on Sunday or Saturday,\n use day thereafter (Monday) instead.\n Needed for holidays such as Christmas observation in Europe\n "
] |
Please provide a description of the function:def nearest_workday(dt):
if dt.weekday() == 5:
return dt - timedelta(1)
elif dt.weekday() == 6:
return dt + timedelta(1)
return dt | [
"\n If holiday falls on Saturday, use day before (Friday) instead;\n if holiday falls on Sunday, use day thereafter (Monday) instead.\n "
] |
Please provide a description of the function:def next_workday(dt):
dt += timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt += timedelta(days=1)
return dt | [
"\n returns next weekday used for observances\n "
] |
Please provide a description of the function:def previous_workday(dt):
dt -= timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt -= timedelta(days=1)
return dt | [
"\n returns previous weekday used for observances\n "
] |
Please provide a description of the function:def dates(self, start_date, end_date, return_name=False):
start_date = Timestamp(start_date)
end_date = Timestamp(end_date)
filter_start_date = start_date
filter_end_date = end_date
if self.year is not None:
dt =... | [
"\n Calculate holidays observed between start date and end date\n\n Parameters\n ----------\n start_date : starting date, datetime-like, optional\n end_date : ending date, datetime-like, optional\n return_name : bool, optional, default=False\n If True, return a s... |
Please provide a description of the function:def _reference_dates(self, start_date, end_date):
if self.start_date is not None:
start_date = self.start_date.tz_localize(start_date.tz)
if self.end_date is not None:
end_date = self.end_date.tz_localize(start_date.tz)
... | [
"\n Get reference dates for the holiday.\n\n Return reference dates for the holiday also returning the year\n prior to the start_date and year following the end_date. This ensures\n that any offsets to be applied will yield the holidays within\n the passed in dates.\n "
] |
Please provide a description of the function:def _apply_rule(self, dates):
if self.observance is not None:
return dates.map(lambda d: self.observance(d))
if self.offset is not None:
if not isinstance(self.offset, list):
offsets = [self.offset]
... | [
"\n Apply the given offset/observance to a DatetimeIndex of dates.\n\n Parameters\n ----------\n dates : DatetimeIndex\n Dates to apply the given offset/observance rule\n\n Returns\n -------\n Dates with rules applied\n "
] |
Please provide a description of the function:def holidays(self, start=None, end=None, return_name=False):
if self.rules is None:
raise Exception('Holiday Calendar {name} does not have any '
'rules specified'.format(name=self.name))
if start is None:
... | [
"\n Returns a curve with holidays between start_date and end_date\n\n Parameters\n ----------\n start : starting date, datetime-like, optional\n end : ending date, datetime-like, optional\n return_name : bool, optional\n If True, return a series that has dates an... |
Please provide a description of the function:def merge_class(base, other):
try:
other = other.rules
except AttributeError:
pass
if not isinstance(other, list):
other = [other]
other_holidays = {holiday.name: holiday for holiday in other}
... | [
"\n Merge holiday calendars together. The base calendar\n will take precedence to other. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n base : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects\n oth... |
Please provide a description of the function:def merge(self, other, inplace=False):
holidays = self.merge_class(self, other)
if inplace:
self.rules = holidays
else:
return holidays | [
"\n Merge holiday calendars together. The caller's class\n rules take precedence. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n other : holiday calendar\n inplace : bool (default=False)\n If True set rule_table to h... |
Please provide a description of the function:def register_option(key, defval, doc='', validator=None, cb=None):
import tokenize
import keyword
key = key.lower()
if key in _registered_options:
msg = "Option '{key}' has already been registered"
raise OptionError(msg.format(key=key))
... | [
"Register an option in the package-wide pandas config object\n\n Parameters\n ----------\n key - a fully-qualified key, e.g. \"x.y.option - z\".\n defval - the default value of the option\n doc - a string description of the option\n validator - a function of a single argument, shoul... |
Please provide a description of the function:def deprecate_option(key, msg=None, rkey=None, removal_ver=None):
key = key.lower()
if key in _deprecated_options:
msg = "Option '{key}' has already been defined as deprecated."
raise OptionError(msg.format(key=key))
_deprecated_options[ke... | [
"\n Mark option `key` as deprecated, if code attempts to access this option,\n a warning will be produced, using `msg` if given, or a default message\n if not.\n if `rkey` is given, any access to the key will be re-routed to `rkey`.\n\n Neither the existence of `key` nor that if `rkey` is checked. If... |
Please provide a description of the function:def _select_options(pat):
# short-circuit for exact key
if pat in _registered_options:
return [pat]
# else look through all of them
keys = sorted(_registered_options.keys())
if pat == 'all': # reserved key
return keys
return [... | [
"returns a list of keys matching `pat`\n\n if pat==\"all\", returns all registered options\n "
] |
Please provide a description of the function:def _translate_key(key):
d = _get_deprecated_option(key)
if d:
return d.rkey or key
else:
return key | [
"\n if key id deprecated and a replacement key defined, will return the\n replacement key, otherwise returns `key` as - is\n "
] |
Please provide a description of the function:def _build_option_description(k):
o = _get_registered_option(k)
d = _get_deprecated_option(k)
s = '{k} '.format(k=k)
if o.doc:
s += '\n'.join(o.doc.strip().split('\n'))
else:
s += 'No description available.'
if o:
s +=... | [
" Builds a formatted description of a registered option and prints it "
] |
Please provide a description of the function:def config_prefix(prefix):
# Note: reset_option relies on set_option, and on key directly
# it does not fit in to this monkey-patching scheme
global register_option, get_option, set_option, reset_option
def wrap(func):
def inner(key, *args, **... | [
"contextmanager for multiple invocations of API with a common prefix\n\n supported API functions: (register / get / set )__option\n\n Warning: This is not thread - safe, and won't work properly if you import\n the API functions into your module using the \"from x import y\" construct.\n\n Example:\n\n ... |
Please provide a description of the function:def parse(self, declarations_str):
for decl in declarations_str.split(';'):
if not decl.strip():
continue
prop, sep, val = decl.partition(':')
prop = prop.strip().lower()
# TODO: don't lowercase... | [
"Generates (prop, value) pairs from declarations\n\n In a future version may generate parsed tokens from tinycss/tinycss2\n "
] |
Please provide a description of the function:def array(data: Sequence[object],
dtype: Optional[Union[str, np.dtype, ExtensionDtype]] = None,
copy: bool = True,
) -> ABCExtensionArray:
from pandas.core.arrays import (
period_array, ExtensionArray, IntervalArray, PandasArray... | [
"\n Create an array.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n data : Sequence of objects\n The scalars inside `data` should be instances of the\n scalar type for `dtype`. It's expected that `data`\n represents a 1-dimensional array of data.\n\n When `data... |
Please provide a description of the function:def maybe_convert_platform_interval(values):
if isinstance(values, (list, tuple)) and len(values) == 0:
# GH 19016
# empty lists/tuples get object dtype by default, but this is not
# prohibited for IntervalArray, so coerce to integer instead
... | [
"\n Try to do platform conversion, with special casing for IntervalArray.\n Wrapper around maybe_convert_platform that alters the default return\n dtype in certain cases to be compatible with IntervalArray. For example,\n empty lists return with integer dtype instead of object dtype, which is\n proh... |
Please provide a description of the function:def is_file_like(obj):
if not (hasattr(obj, 'read') or hasattr(obj, 'write')):
return False
if not hasattr(obj, "__iter__"):
return False
return True | [
"\n Check if the object is a file-like object.\n\n For objects to be considered file-like, they must\n be an iterator AND have either a `read` and/or `write`\n method as an attribute.\n\n Note: file-like objects must be iterable, but\n iterable objects need not be file-like.\n\n .. versionadded... |
Please provide a description of the function:def is_list_like(obj, allow_sets=True):
return (isinstance(obj, abc.Iterable) and
# we do not count strings/unicode/bytes as list-like
not isinstance(obj, (str, bytes)) and
# exclude zero-dimensional numpy arrays, effectively sc... | [
"\n Check if the object is list-like.\n\n Objects that are considered list-like are for example Python\n lists, tuples, sets, NumPy arrays, and Pandas Series.\n\n Strings and datetime objects, however, are not considered list-like.\n\n Parameters\n ----------\n obj : The object to check\n al... |
Please provide a description of the function:def is_nested_list_like(obj):
return (is_list_like(obj) and hasattr(obj, '__len__') and
len(obj) > 0 and all(is_list_like(item) for item in obj)) | [
"\n Check if the object is list-like, and that all of its elements\n are also list-like.\n\n .. versionadded:: 0.20.0\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_list_like : bool\n Whether `obj` has list-like properties.\n\n Examples\n -... |
Please provide a description of the function:def is_dict_like(obj):
dict_like_attrs = ("__getitem__", "keys", "__contains__")
return (all(hasattr(obj, attr) for attr in dict_like_attrs)
# [GH 25196] exclude classes
and not isinstance(obj, type)) | [
"\n Check if the object is dict-like.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_dict_like : bool\n Whether `obj` has dict-like properties.\n\n Examples\n --------\n >>> is_dict_like({1: 2})\n True\n >>> is_dict_like([1, 2, 3])\n ... |
Please provide a description of the function:def is_sequence(obj):
try:
iter(obj) # Can iterate over it.
len(obj) # Has a length associated with it.
return not isinstance(obj, (str, bytes))
except (TypeError, AttributeError):
return False | [
"\n Check if the object is a sequence of objects.\n String types are not included as sequences here.\n\n Parameters\n ----------\n obj : The object to check\n\n Returns\n -------\n is_sequence : bool\n Whether `obj` is a sequence of objects.\n\n Examples\n --------\n >>> l = ... |
Please provide a description of the function:def _new_DatetimeIndex(cls, d):
if "data" in d and not isinstance(d["data"], DatetimeIndex):
# Avoid need to verify integrity by calling simple_new directly
data = d.pop("data")
result = cls._simple_new(data, **d)
else:
with warn... | [
" This is called upon unpickling, rather than the default which doesn't\n have arguments and breaks __new__ "
] |
Please provide a description of the function:def date_range(start=None, end=None, periods=None, freq=None, tz=None,
normalize=False, name=None, closed=None, **kwargs):
if freq is None and com._any_none(periods, start, end):
freq = 'D'
dtarr = DatetimeArray._generate_range(
... | [
"\n Return a fixed frequency DatetimeIndex.\n\n Parameters\n ----------\n start : str or datetime-like, optional\n Left bound for generating dates.\n end : str or datetime-like, optional\n Right bound for generating dates.\n periods : integer, optional\n Number of periods to g... |
Please provide a description of the function:def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,
normalize=True, name=None, weekmask=None, holidays=None,
closed=None, **kwargs):
if freq is None:
msg = 'freq must be specified for bdate_range; use date_r... | [
"\n Return a fixed frequency DatetimeIndex, with business day as the default\n frequency\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates.\n end : string or datetime-like, default None\n Right bound for generating dates.\n ... |
Please provide a description of the function:def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
normalize=True, name=None, closed=None, **kwargs):
warnings.warn("cdate_range is deprecated and will be removed in a future "
"version, instead use pd.bdate_rang... | [
"\n Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the\n default frequency\n\n .. deprecated:: 0.21.0\n\n Parameters\n ----------\n start : string or datetime-like, default None\n Left bound for generating dates\n end : string or datetime-like, default None\n Ri... |
Please provide a description of the function:def _create_blocks(self):
obj, index = self._convert_freq()
if index is not None:
index = self._on
# filter out the on from the object
if self.on is not None:
if obj.ndim == 2:
obj = obj.reind... | [
"\n Split data into blocks & return conformed data.\n "
] |
Please provide a description of the function:def _gotitem(self, key, ndim, subset=None):
# create a new object to prevent aliasing
if subset is None:
subset = self.obj
self = self._shallow_copy(subset)
self._reset_cache()
if subset.ndim == 2:
if ... | [
"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : str / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n "
] |
Please provide a description of the function:def _get_index(self, index=None):
if self.is_freq_type:
if index is None:
index = self._on
return index, index.asi8
return index, index | [
"\n Return index as ndarrays.\n\n Returns\n -------\n tuple of (index, index_as_ndarray)\n "
] |
Please provide a description of the function:def _wrap_result(self, result, block=None, obj=None):
if obj is None:
obj = self._selected_obj
index = obj.index
if isinstance(result, np.ndarray):
# coerce if necessary
if block is not None:
... | [
"\n Wrap a single result.\n "
] |
Please provide a description of the function:def _wrap_results(self, results, blocks, obj):
from pandas import Series, concat
from pandas.core.index import ensure_index
final = []
for result, block in zip(results, blocks):
result = self._wrap_result(result, block=... | [
"\n Wrap the results.\n\n Parameters\n ----------\n results : list of ndarrays\n blocks : list of blocks\n obj : conformed data (may be resampled)\n "
] |
Please provide a description of the function:def _center_window(self, result, window):
if self.axis > result.ndim - 1:
raise ValueError("Requested axis is larger then no. of argument "
"dimensions")
offset = _offset(window, True)
if offset > 0:
... | [
"\n Center the result in the window.\n "
] |
Please provide a description of the function:def _prep_window(self, **kwargs):
window = self._get_window()
if isinstance(window, (list, tuple, np.ndarray)):
return com.asarray_tuplesafe(window).astype(float)
elif is_integer(window):
import scipy.signal as sig
... | [
"\n Provide validation for our window type, return the window\n we have already been validated.\n "
] |
Please provide a description of the function:def _apply_window(self, mean=True, **kwargs):
window = self._prep_window(**kwargs)
center = self.center
blocks, obj, index = self._create_blocks()
results = []
for b in blocks:
try:
values = self._... | [
"\n Applies a moving window of type ``window_type`` on the data.\n\n Parameters\n ----------\n mean : bool, default True\n If True computes weighted mean, else weighted sum\n\n Returns\n -------\n y : same type as input argument\n\n "
] |
Please provide a description of the function:def _apply(self, func, name, window=None, center=None,
check_minp=None, **kwargs):
def f(x, name=name, *args):
x = self._shallow_copy(x)
if isinstance(name, str):
return getattr(x, name)(*args, **kwarg... | [
"\n Dispatch to apply; we are stripping all of the _apply kwargs and\n performing the original function call on the grouped object.\n "
] |
Please provide a description of the function:def _apply(self, func, name=None, window=None, center=None,
check_minp=None, **kwargs):
if center is None:
center = self.center
if window is None:
window = self._get_window()
if check_minp is None:
... | [
"\n Rolling statistical measure using supplied function.\n\n Designed to be used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : str/callable to apply\n name : str, optional\n name of this function\n window : int/array, def... |
Please provide a description of the function:def _validate_monotonic(self):
if not self._on.is_monotonic:
formatted = self.on or 'index'
raise ValueError("{0} must be "
"monotonic".format(formatted)) | [
"\n Validate on is_monotonic.\n "
] |
Please provide a description of the function:def _validate_freq(self):
from pandas.tseries.frequencies import to_offset
try:
return to_offset(self.window)
except (TypeError, ValueError):
raise ValueError("passed window {0} is not "
"c... | [
"\n Validate & return window frequency.\n "
] |
Please provide a description of the function:def _get_window(self, other=None):
axis = self.obj._get_axis(self.axis)
length = len(axis) + (other is not None) * len(axis)
other = self.min_periods or -1
return max(length, other) | [
"\n Get the window length over which to perform some operation.\n\n Parameters\n ----------\n other : object, default None\n The other object that is involved in the operation.\n Such an object is involved for operations like covariance.\n\n Returns\n ... |
Please provide a description of the function:def _apply(self, func, **kwargs):
blocks, obj, index = self._create_blocks()
results = []
for b in blocks:
try:
values = self._prep_values(b.values)
except TypeError:
results.append(b.va... | [
"\n Rolling statistical measure using supplied function. Designed to be\n used with passed-in Cython array-based functions.\n\n Parameters\n ----------\n func : str/callable to apply\n\n Returns\n -------\n y : same type as input argument\n "
] |
Please provide a description of the function:def mean(self, *args, **kwargs):
nv.validate_window_func('mean', args, kwargs)
return self._apply('ewma', **kwargs) | [
"\n Exponential weighted moving average.\n\n Parameters\n ----------\n *args, **kwargs\n Arguments and keyword arguments to be passed into func.\n "
] |
Please provide a description of the function:def std(self, bias=False, *args, **kwargs):
nv.validate_window_func('std', args, kwargs)
return _zsqrt(self.var(bias=bias, **kwargs)) | [
"\n Exponential weighted moving stddev.\n "
] |
Please provide a description of the function:def var(self, bias=False, *args, **kwargs):
nv.validate_window_func('var', args, kwargs)
def f(arg):
return libwindow.ewmcov(arg, arg, self.com, int(self.adjust),
int(self.ignore_na), int(self.min_peri... | [
"\n Exponential weighted moving variance.\n "
] |
Please provide a description of the function:def cov(self, other=None, pairwise=None, bias=False, **kwargs):
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
... | [
"\n Exponential weighted sample covariance.\n "
] |
Please provide a description of the function:def corr(self, other=None, pairwise=None, **kwargs):
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
de... | [
"\n Exponential weighted sample correlation.\n "
] |
Please provide a description of the function:def _ensure_like_indices(time, panels):
n_time = len(time)
n_panel = len(panels)
u_panels = np.unique(panels) # this sorts!
u_time = np.unique(time)
if len(u_time) == n_time:
time = np.tile(u_time, len(u_panels))
if len(u_panels) == n_pa... | [
"\n Makes sure that time and panels are conformable.\n "
] |
Please provide a description of the function:def panel_index(time, panels, names=None):
if names is None:
names = ['time', 'panel']
time, panels = _ensure_like_indices(time, panels)
return MultiIndex.from_arrays([time, panels], sortorder=None, names=names) | [
"\n Returns a multi-index suitable for a panel-like DataFrame.\n\n Parameters\n ----------\n time : array-like\n Time index, does not have to repeat\n panels : array-like\n Panel index, does not have to repeat\n names : list, optional\n List containing the names of the indices... |
Please provide a description of the function:def _init_data(self, data, copy, dtype, **kwargs):
if data is None:
data = {}
if dtype is not None:
dtype = self._validate_dtype(dtype)
passed_axes = [kwargs.pop(a, None) for a in self._AXIS_ORDERS]
if kwargs... | [
"\n Generate ND initialization; axes are passed\n as required objects to __init__.\n "
] |
Please provide a description of the function:def from_dict(cls, data, intersect=False, orient='items', dtype=None):
from collections import defaultdict
orient = orient.lower()
if orient == 'minor':
new_data = defaultdict(OrderedDict)
for col, df in data.items():... | [
"\n Construct Panel from dict of DataFrame objects.\n\n Parameters\n ----------\n data : dict\n {field : DataFrame}\n intersect : boolean\n Intersect indexes of input DataFrames\n orient : {'items', 'minor'}, default 'items'\n The \"orientat... |
Please provide a description of the function:def _get_plane_axes_index(self, axis):
axis_name = self._get_axis_name(axis)
if axis_name == 'major_axis':
index = 'minor_axis'
columns = 'items'
if axis_name == 'minor_axis':
index = 'major_axis'
... | [
"\n Get my plane axes indexes: these are already\n (as compared with higher level planes),\n as we are returning a DataFrame axes indexes.\n "
] |
Please provide a description of the function:def _get_plane_axes(self, axis):
return [self._get_axis(axi)
for axi in self._get_plane_axes_index(axis)] | [
"\n Get my plane axes indexes: these are already\n (as compared with higher level planes),\n as we are returning a DataFrame axes.\n "
] |
Please provide a description of the function:def to_excel(self, path, na_rep='', engine=None, **kwargs):
from pandas.io.excel import ExcelWriter
if isinstance(path, str):
writer = ExcelWriter(path, engine=engine)
else:
writer = path
kwargs['na_rep'] = na... | [
"\n Write each DataFrame in Panel to a separate excel sheet.\n\n Parameters\n ----------\n path : string or ExcelWriter object\n File path or existing ExcelWriter\n na_rep : string, default ''\n Missing data representation\n engine : string, default No... |
Please provide a description of the function:def get_value(self, *args, **kwargs):
warnings.warn("get_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
stackl... | [
"\n Quickly retrieve single value at (item, major, minor) location.\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n item : item label (panel item)\n major : major axis label (panel item row)\n minor : minor ax... |
Please provide a description of the function:def set_value(self, *args, **kwargs):
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
".at[] or .iat[] accessors instead", FutureWarning,
stackl... | [
"\n Quickly set single value at (item, major, minor) location.\n\n .. deprecated:: 0.21.0\n\n Please use .at[] or .iat[] accessors.\n\n Parameters\n ----------\n item : item label (panel item)\n major : major axis label (panel item row)\n minor : minor axis la... |
Please provide a description of the function:def _unpickle_panel_compat(self, state): # pragma: no cover
from pandas.io.pickle import _unpickle_array
_unpickle = _unpickle_array
vals, items, major, minor = state
items = _unpickle(items)
major = _unpickle(major)
... | [
"\n Unpickle the panel.\n "
] |
Please provide a description of the function:def conform(self, frame, axis='items'):
axes = self._get_plane_axes(axis)
return frame.reindex(**self._extract_axes_for_slice(self, axes)) | [
"\n Conform input DataFrame to align with chosen axis pair.\n\n Parameters\n ----------\n frame : DataFrame\n axis : {'items', 'major', 'minor'}\n\n Axis the input corresponds to. E.g., if axis='major', then\n the frame's columns would be items, and the index... |
Please provide a description of the function:def round(self, decimals=0, *args, **kwargs):
nv.validate_round(args, kwargs)
if is_integer(decimals):
result = np.apply_along_axis(np.round, 0, self.values)
return self._wrap_result(result, axis=0)
raise TypeError("d... | [
"\n Round each value in Panel to a specified number of decimal places.\n\n .. versionadded:: 0.18.0\n\n Parameters\n ----------\n decimals : int\n Number of decimal places to round to (default: 0).\n If decimals is negative, it specifies the number of\n ... |
Please provide a description of the function:def dropna(self, axis=0, how='any', inplace=False):
axis = self._get_axis_number(axis)
values = self.values
mask = notna(values)
for ax in reversed(sorted(set(range(self._AXIS_LEN)) - {axis})):
mask = mask.sum(ax)
... | [
"\n Drop 2D from panel, holding passed axis constant.\n\n Parameters\n ----------\n axis : int, default 0\n Axis to hold constant. E.g. axis=1 will drop major_axis entries\n having a certain amount of NA data\n how : {'all', 'any'}, default 'any'\n ... |
Please provide a description of the function:def xs(self, key, axis=1):
axis = self._get_axis_number(axis)
if axis == 0:
return self[key]
self._consolidate_inplace()
axis_number = self._get_axis_number(axis)
new_data = self._data.xs(key, axis=axis_number, co... | [
"\n Return slice of panel along selected axis.\n\n Parameters\n ----------\n key : object\n Label\n axis : {'items', 'major', 'minor}, default 1/'major'\n\n Returns\n -------\n y : ndim(self)-1\n\n Notes\n -----\n xs is only for... |
Please provide a description of the function:def _ixs(self, i, axis=0):
ax = self._get_axis(axis)
key = ax[i]
# xs cannot handle a non-scalar key, so just reindex here
# if we have a multi-index and a single tuple, then its a reduction
# (GH 7516)
if not (isins... | [
"\n Parameters\n ----------\n i : int, slice, or sequence of integers\n axis : int\n "
] |
Please provide a description of the function:def to_frame(self, filter_observations=True):
_, N, K = self.shape
if filter_observations:
# shaped like the return DataFrame
mask = notna(self.values).all(axis=0)
# size = mask.sum()
selector = mask.r... | [
"\n Transform wide format into long (stacked) format as DataFrame whose\n columns are the Panel's items and whose index is a MultiIndex formed\n of the Panel's major and minor axes.\n\n Parameters\n ----------\n filter_observations : boolean, default True\n Drop ... |
Please provide a description of the function:def apply(self, func, axis='major', **kwargs):
if kwargs and not isinstance(func, np.ufunc):
f = lambda x: func(x, **kwargs)
else:
f = func
# 2d-slabs
if isinstance(axis, (tuple, list)) and len(axis) == 2:
... | [
"\n Apply function along axis (or axes) of the Panel.\n\n Parameters\n ----------\n func : function\n Function to apply to each combination of 'other' axes\n e.g. if axis = 'items', the combination of major_axis/minor_axis\n will each be passed as a Serie... |
Please provide a description of the function:def _apply_2d(self, func, axis):
ndim = self.ndim
axis = [self._get_axis_number(a) for a in axis]
# construct slabs, in 2-d this is a DataFrame result
indexer_axis = list(range(ndim))
for a in axis:
indexer_axis.r... | [
"\n Handle 2-d slices, equiv to iterating over the other axis.\n "
] |
Please provide a description of the function:def _construct_return_type(self, result, axes=None):
ndim = getattr(result, 'ndim', None)
# need to assume they are the same
if ndim is None:
if isinstance(result, dict):
ndim = getattr(list(result.values())[0], '... | [
"\n Return the type for the ndim of the result.\n "
] |
Please provide a description of the function:def count(self, axis='major'):
i = self._get_axis_number(axis)
values = self.values
mask = np.isfinite(values)
result = mask.sum(axis=i, dtype='int64')
return self._wrap_result(result, axis) | [
"\n Return number of observations over requested axis.\n\n Parameters\n ----------\n axis : {'items', 'major', 'minor'} or {0, 1, 2}\n\n Returns\n -------\n count : DataFrame\n "
] |
Please provide a description of the function:def shift(self, periods=1, freq=None, axis='major'):
if freq:
return self.tshift(periods, freq, axis=axis)
return super().slice_shift(periods, axis=axis) | [
"\n Shift index by desired number of periods with an optional time freq.\n\n The shifted data will not include the dropped periods and the\n shifted axis will be smaller than the original. This is different\n from the behavior of DataFrame.shift()\n\n Parameters\n ---------... |
Please provide a description of the function:def join(self, other, how='left', lsuffix='', rsuffix=''):
from pandas.core.reshape.concat import concat
if isinstance(other, Panel):
join_major, join_minor = self._get_join_index(other, how)
this = self.reindex(major=join_ma... | [
"\n Join items with other Panel either on major and minor axes column.\n\n Parameters\n ----------\n other : Panel or list of Panels\n Index should be similar to one of the columns in this one\n how : {'left', 'right', 'outer', 'inner'}\n How to handle indexe... |
Please provide a description of the function:def update(self, other, join='left', overwrite=True, filter_func=None,
errors='ignore'):
if not isinstance(other, self._constructor):
other = self._constructor(other)
axis_name = self._info_axis_name
axis_values =... | [
"\n Modify Panel in place using non-NA values from other Panel.\n\n May also use object coercible to Panel. Will align on items.\n\n Parameters\n ----------\n other : Panel, or object coercible to Panel\n The object from which the caller will be udpated.\n join :... |
Please provide a description of the function:def _extract_axes(self, data, axes, **kwargs):
return [self._extract_axis(self, data, axis=i, **kwargs)
for i, a in enumerate(axes)] | [
"\n Return a list of the axis indices.\n "
] |
Please provide a description of the function:def _extract_axes_for_slice(self, axes):
return {self._AXIS_SLICEMAP[i]: a for i, a in
zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)} | [
"\n Return the slice dictionary for these axes.\n "
] |
Please provide a description of the function:def _homogenize_dict(self, frames, intersect=True, dtype=None):
result = dict()
# caller differs dict/ODict, preserved type
if isinstance(frames, OrderedDict):
result = OrderedDict()
adj_frames = OrderedDict()
fo... | [
"\n Conform set of _constructor_sliced-like objects to either\n an intersection of indices / columns or a union.\n\n Parameters\n ----------\n frames : dict\n intersect : boolean, default True\n\n Returns\n -------\n dict of aligned results & indices\n ... |
Please provide a description of the function:def get_group_index(labels, shape, sort, xnull):
def _int64_cut_off(shape):
acc = 1
for i, mul in enumerate(shape):
acc *= int(mul)
if not acc < _INT64_MAX:
return i
return len(shape)
def maybe_lif... | [
"\n For the particular label_list, gets the offsets into the hypothetical list\n representing the totally ordered cartesian product of all possible label\n combinations, *as long as* this space fits within int64 bounds;\n otherwise, though group indices identify unique combinations of\n labels, they ... |
Please provide a description of the function:def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull):
if not xnull:
lift = np.fromiter(((a == -1).any() for a in labels), dtype='i8')
shape = np.asarray(shape, dtype='i8') + lift
if not is_int64_overflow_possible(shape):
# ... | [
"\n reconstruct labels from observed group ids\n\n Parameters\n ----------\n xnull: boolean,\n if nulls are excluded; i.e. -1 labels are passed through\n "
] |
Please provide a description of the function:def nargsort(items, kind='quicksort', ascending=True, na_position='last'):
# specially handle Categorical
if is_categorical_dtype(items):
if na_position not in {'first', 'last'}:
raise ValueError('invalid na_position: {!r}'.format(na_positio... | [
"\n This is intended to be a drop-in replacement for np.argsort which\n handles NaNs. It adds ascending and na_position parameters.\n GH #6399, #5231\n "
] |
Please provide a description of the function:def get_indexer_dict(label_list, keys):
shape = list(map(len, keys))
group_index = get_group_index(label_list, shape, sort=True, xnull=True)
ngroups = ((group_index.size and group_index.max()) + 1) \
if is_int64_overflow_possible(shape) \
el... | [
" return a diction of {labels} -> {indexers} "
] |
Please provide a description of the function:def get_group_index_sorter(group_index, ngroups):
count = len(group_index)
alpha = 0.0 # taking complexities literally; there may be
beta = 1.0 # some room for fine-tuning these parameters
do_groupsort = (count > 0 and ((alpha + beta * ngroups) <
... | [
"\n algos.groupsort_indexer implements `counting sort` and it is at least\n O(ngroups), where\n ngroups = prod(shape)\n shape = map(len, keys)\n that is, linear in the number of combinations (cartesian product) of unique\n values of groupby keys. This can be huge when doing multi-key group... |
Please provide a description of the function:def compress_group_index(group_index, sort=True):
size_hint = min(len(group_index), hashtable._SIZE_HINT_LIMIT)
table = hashtable.Int64HashTable(size_hint)
group_index = ensure_int64(group_index)
# note, group labels come out ascending (ie, 1,2,3 etc)... | [
"\n Group_index is offsets into cartesian product of all possible labels. This\n space can be huge, so this function compresses it, by computing offsets\n (comp_ids) into the list of unique labels (obs_group_ids).\n "
] |
Please provide a description of the function:def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False):
if not is_list_like(values):
raise TypeError("Only list-like objects are allowed to be passed to"
"safe_sort as values")
if not isinstance(values, np.ndarra... | [
"\n Sort ``values`` and reorder corresponding ``labels``.\n ``values`` should be unique if ``labels`` is not None.\n Safe for use with mixed types (int, str), orders ints before strs.\n\n .. versionadded:: 0.19.0\n\n Parameters\n ----------\n values : list-like\n Sequence; must be unique... |
Please provide a description of the function:def _check_ne_builtin_clash(expr):
names = expr.names
overlap = names & _ne_builtins
if overlap:
s = ', '.join(map(repr, overlap))
raise NumExprClobberingError('Variables in expression "{expr}" '
'overlap... | [
"Attempt to prevent foot-shooting in a helpful way.\n\n Parameters\n ----------\n terms : Term\n Terms can contain\n "
] |
Please provide a description of the function:def evaluate(self):
if not self._is_aligned:
self.result_type, self.aligned_axes = _align(self.expr.terms)
# make sure no names in resolvers and locals/globals clash
res = self._evaluate()
return _reconstruct_object(self.... | [
"Run the engine on the expression\n\n This method performs alignment which is necessary no matter what engine\n is being used, thus its implementation is in the base class.\n\n Returns\n -------\n obj : object\n The result of the passed expression.\n "
] |
Please provide a description of the function:def get_block_type(values, dtype=None):
dtype = dtype or values.dtype
vtype = dtype.type
if is_sparse(dtype):
# Need this first(ish) so that Sparse[datetime] is sparse
cls = ExtensionBlock
elif is_categorical(values):
cls = Categ... | [
"\n Find the appropriate Block subclass to use for the given values and dtype.\n\n Parameters\n ----------\n values : ndarray-like\n dtype : numpy or pandas dtype\n\n Returns\n -------\n cls : class, subclass of Block\n "
] |
Please provide a description of the function:def _extend_blocks(result, blocks=None):
from pandas.core.internals import BlockManager
if blocks is None:
blocks = []
if isinstance(result, list):
for r in result:
if isinstance(r, list):
blocks.extend(r)
... | [
" return a new extended blocks, givin the result "
] |
Please provide a description of the function:def _block_shape(values, ndim=1, shape=None):
if values.ndim < ndim:
if shape is None:
shape = values.shape
if not is_extension_array_dtype(values):
# TODO: https://github.com/pandas-dev/pandas/issues/23023
# block... | [
" guarantee the shape of the values to be at least 1 d "
] |
Please provide a description of the function:def _safe_reshape(arr, new_shape):
if isinstance(arr, ABCSeries):
arr = arr._values
if not isinstance(arr, ABCExtensionArray):
arr = arr.reshape(new_shape)
return arr | [
"\n If possible, reshape `arr` to have shape `new_shape`,\n with a couple of exceptions (see gh-13012):\n\n 1) If `arr` is a ExtensionArray or Index, `arr` will be\n returned as is.\n 2) If `arr` is a Series, the `_values` attribute will\n be reshaped and returned.\n\n Parameters\n ---... |
Please provide a description of the function:def _putmask_smart(v, m, n):
# we cannot use np.asarray() here as we cannot have conversions
# that numpy does when numeric are mixed with strings
# n should be the length of the mask or a scalar here
if not is_list_like(n):
n = np.repeat(n, le... | [
"\n Return a new ndarray, try to preserve dtype if possible.\n\n Parameters\n ----------\n v : `values`, updated in-place (array like)\n m : `mask`, applies to both sides (array like)\n n : `new values` either scalar or an array like aligned with `values`\n\n Returns\n -------\n values : ... |
Please provide a description of the function:def _check_ndim(self, values, ndim):
if ndim is None:
ndim = values.ndim
if self._validate_ndim and values.ndim != ndim:
msg = ("Wrong number of dimensions. values.ndim != ndim "
"[{} != {}]")
r... | [
"\n ndim inference and validation.\n\n Infers ndim from 'values' if not provided to __init__.\n Validates that values.ndim and ndim are consistent if and only if\n the class variable '_validate_ndim' is True.\n\n Parameters\n ----------\n values : array-like\n ... |
Please provide a description of the function:def is_categorical_astype(self, dtype):
if dtype is Categorical or dtype is CategoricalDtype:
# this is a pd.Categorical, but is not
# a valid type for astypeing
raise TypeError("invalid type {0} for astype".format(dtype))... | [
"\n validate that we have a astypeable to categorical,\n returns a boolean if we are a categorical\n "
] |
Please provide a description of the function:def get_values(self, dtype=None):
if is_object_dtype(dtype):
return self.values.astype(object)
return self.values | [
"\n return an internal format, currently just the ndarray\n this is often overridden to handle to_dense like operations\n "
] |
Please provide a description of the function:def make_block(self, values, placement=None, ndim=None):
if placement is None:
placement = self.mgr_locs
if ndim is None:
ndim = self.ndim
return make_block(values, placement=placement, ndim=ndim) | [
"\n Create a new block, with type inference propagate any values that are\n not specified\n "
] |
Please provide a description of the function:def make_block_same_class(self, values, placement=None, ndim=None,
dtype=None):
if dtype is not None:
# issue 19431 fastparquet is passing this
warnings.warn("dtype argument is deprecated, will be removed... | [
" Wrap given values in a block of same type as self. "
] |
Please provide a description of the function:def getitem_block(self, slicer, new_mgr_locs=None):
if new_mgr_locs is None:
if isinstance(slicer, tuple):
axis0_slicer = slicer[0]
else:
axis0_slicer = slicer
new_mgr_locs = self.mgr_locs[a... | [
"\n Perform __getitem__-like, return result as block.\n\n As of now, only supports slices that preserve dimensionality.\n "
] |
Please provide a description of the function:def concat_same_type(self, to_concat, placement=None):
values = self._concatenator([blk.values for blk in to_concat],
axis=self.ndim - 1)
return self.make_block_same_class(
values, placement=placement o... | [
"\n Concatenate list of single blocks of the same type.\n "
] |
Please provide a description of the function:def delete(self, loc):
self.values = np.delete(self.values, loc, 0)
self.mgr_locs = self.mgr_locs.delete(loc) | [
"\n Delete given loc(-s) from block in-place.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.