text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attr(self): """ set the data for this column """
setattr(self.attrs, self.kind_attr, self.values) setattr(self.attrs, self.meta_attr, self.meta) if self.dtype is not None: setattr(self.attrs, self.dtype_attr, self.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_version(self): """ compute and set our version """
version = _ensure_decoded( getattr(self.group._v_attrs, 'pandas_version', None)) try: self.version = tuple(int(x) for x in version.split('.')) if len(self.version) == 2: self.version = self.version + (0,) except AttributeError: sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_object_info(self): """ set my pandas type & version """
self.attrs.pandas_type = str(self.pandas_kind) self.attrs.pandas_version = str(_version) self.set_version()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def infer_axes(self): """ infer the axes of my storer return a boolean indicating if we have a valid storer or not """
s = self.storable if s is None: return False self.get_attrs() return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_read(self, kwargs): """ remove table keywords from kwargs and return raise if any keywords are passed which are not-None """
kwargs = copy.copy(kwargs) columns = kwargs.pop('columns', None) if columns is not None: raise TypeError("cannot pass a column specification when reading " "a Fixed format store. this store must be " "selected in its entirety"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attrs(self): """ set our object attributes """
self.attrs.encoding = self.encoding self.attrs.errors = self.errors
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_array(self, key, start=None, stop=None): """ read an array for the specified node (off of group """
import tables node = getattr(self.group, key) attrs = node._v_attrs transposed = getattr(attrs, 'transposed', False) if isinstance(node, tables.VLArray): ret = node[0][start:stop] else: dtype = getattr(attrs, 'value_type', None) shap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_array_empty(self, key, value): """ write a 0-len array """
# ugly hack for length 0 axes arr = np.empty((1,) * value.ndim) self._handle.create_array(self.group, key, arr) getattr(self.group, key)._v_attrs.value_type = str(value.dtype) getattr(self.group, key)._v_attrs.shape = value.shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_read(self, kwargs): """ we don't support start, stop kwds in Sparse """
kwargs = super().validate_read(kwargs) if 'start' in kwargs or 'stop' in kwargs: raise NotImplementedError("start and/or stop are not supported " "in fixed Sparse reading") return kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, obj, **kwargs): """ write it as a collection of individual sparse series """
super().write(obj, **kwargs) for name, ss in obj.items(): key = 'sparse_series_{name}'.format(name=name) if key not in self.group._v_children: node = self._handle.create_group(self.group, key) else: node = getattr(self.group, key) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, other): """ validate against an existing table """
if other is None: return if other.table_type != self.table_type: raise TypeError( "incompatible table_type with existing " "[{other} - {self}]".format( other=other.table_type, self=self.table_type)) for c in ['index_a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_multiindex(self, obj): """validate that we can store the multi-index; reset and return the new object """
levels = [l if l is not None else "level_{0}".format(i) for i, l in enumerate(obj.index.names)] try: return obj.reset_index(), levels except ValueError: raise ValueError("duplicate names/columns in the multi-index when " "st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nrows_expected(self): """ based on our axes, compute the expected nrows """
return np.prod([i.cvalues.shape[0] for i in self.index_axes])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_orientation(self): """return a tuple of my permutated axes, non_indexable at the front"""
return tuple(itertools.chain([int(a[0]) for a in self.non_index_axes], [int(a.axis) for a in self.index_axes]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queryables(self): """ return a dict of the kinds allowable columns for this object """
# compute the values_axes queryables return dict( [(a.cname, a) for a in self.index_axes] + [(self.storage_obj_type._AXIS_NAMES[axis], None) for axis, values in self.non_index_axes] + [(v.cname, v) for v in self.values_axes if v.name in set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_metadata_path(self, key): """ return the metadata pathname for this key """
return "{group}/meta/{key}/meta".format(group=self.group._v_pathname, key=key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_metadata(self, key, values): """ write out a meta data array to the key as a fixed-format Series Parameters key : string values : ndarray """
values = Series(values) self.parent.put(self._get_metadata_path(key), values, format='table', encoding=self.encoding, errors=self.errors, nan_rep=self.nan_rep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_metadata(self, key): """ return the meta data array for this key """
if getattr(getattr(self.group, 'meta', None), key, None) is not None: return self.parent.select(self._get_metadata_path(key)) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attrs(self): """ set our table type & indexables """
self.attrs.table_type = str(self.table_type) self.attrs.index_cols = self.index_cols() self.attrs.values_cols = self.values_cols() self.attrs.non_index_axes = self.non_index_axes self.attrs.data_columns = self.data_columns self.attrs.nan_rep = self.nan_rep self.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_version(self, where=None): """ are we trying to operate on an old version? """
if where is not None: if (self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1): ws = incompatibility_doc % '.'.join( [str(x) for x in self.version]) warnings.warn(ws, IncompatibilityWarning)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_min_itemsize(self, min_itemsize): """validate the min_itemisze doesn't contain items that are not in the axes this needs data_columns to be defined ...
if min_itemsize is None: return if not isinstance(min_itemsize, dict): return q = self.queryables() for k, v in min_itemsize.items(): # ok, apply generally if k == 'values': continue if k not in q: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_data_columns(self, data_columns, min_itemsize): """take the input data_columns and min_itemize and create a data columns spec """
if not len(self.non_index_axes): return [] axis, axis_labels = self.non_index_axes[0] info = self.info.get(axis, dict()) if info.get('type') == 'MultiIndex' and data_columns: raise ValueError("cannot use a multi-index on axis [{0}] with " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_axes(self, obj, columns=None): """ process axes filters """
# make a copy to avoid side effects if columns is not None: columns = list(columns) # make sure to include levels if we have them if columns is not None and self.is_multi_index: for n in self.levels: if n not in columns: colu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_description(self, complib=None, complevel=None, fletcher32=False, expectedrows=None): """ create the description of the table from the axes & values "...
# provided expected rows if its passed if expectedrows is None: expectedrows = max(self.nrows_expected, 10000) d = dict(name='table', expectedrows=expectedrows) # description from the axes & values d['description'] = {a.cname: a.typ for a in self.axes} if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_column(self, column, where=None, start=None, stop=None): """return a single column from the table, generally only indexables are interesting """
# validate the version self.validate_version() # infer the data kind if not self.infer_axes(): return False if where is not None: raise TypeError("read_column does not currently accept a where " "clause") # find the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, where=None, columns=None, **kwargs): """we have n indexable columns, with an arbitrary number of data axes """
if not self.read_axes(where=where, **kwargs): return None raise NotImplementedError("Panel is removed in pandas 0.25.0")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_data(self, chunksize, dropna=False): """ we form the data into a 2-d including indexes,values,mask write chunk-by-chunk """
names = self.dtype.names nrows = self.nrows_expected # if dropna==True, then drop ALL nan rows masks = [] if dropna: for a in self.values_axes: # figure the mask: only do if we can successfully process this # column, otherwise igno...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def indexables(self): """ create the indexables from the table description """
if self._indexables is None: d = self.description # the index columns is just a simple index self._indexables = [GenericIndexCol(name='index', axis=0)] for i, n in enumerate(d._v_names): dc = GenericDataIndexableCol( name=n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def astype(self, dtype, copy=True): """ Cast to a NumPy array with 'dtype'. Parameters dtype : str or dtype Typecode or data-type to which the array is cast. cop...
return np.array(self, dtype=dtype, copy=copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argsort(self, ascending=True, kind='quicksort', *args, **kwargs): """ Return the indices that would sort this array. Parameters ascending : bool, default Tru...
# Implementor note: You have two places to override the behavior of # argsort. # 1. _values_for_argsort : construct the values passed to np.argsort # 2. argsort : total control over sorting. ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs) values =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift( self, periods: int = 1, fill_value: object = None, ) -> ABCExtensionArray: """ Shift values by desired number. Newly introduced missing values are fill...
# Note: this implementation assumes that `self.dtype.na_value` can be # stored in an instance of your ExtensionArray with `self.dtype`. if not len(self) or periods == 0: return self.copy() if isna(fill_value): fill_value = self.dtype.na_value empty = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unique(self): """ Compute the ExtensionArray of unique values. Returns ------- uniques : ExtensionArray """
from pandas import unique uniques = unique(self.astype(object)) return self._from_sequence(uniques, dtype=self.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _values_for_factorize(self) -> Tuple[np.ndarray, Any]: """ Return an array and missing value suitable for factorization. Returns ------- values : ndarray An a...
return self.astype(object), np.nan
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def factorize( self, na_sentinel: int = -1, ) -> Tuple[np.ndarray, ABCExtensionArray]: """ Encode the extension array as an enumerated type. Parameters na_sentine...
# Impelmentor note: There are two ways to override the behavior of # pandas.factorize # 1. _values_for_factorize and _from_factorize. # Specify the values passed to pandas' internal factorization # routines, and how to convert from those values back to the # ori...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatter( self, boxed: bool = False, ) -> Callable[[Any], Optional[str]]: """Formatting function for scalar values. This is used in the default '__repr__'. ...
if boxed: return str return repr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reduce(self, name, skipna=True, **kwargs): """ Return a scalar result of performing the reduction operation. Parameters name : str Name of the function, sup...
raise TypeError("cannot perform {name} with type {dtype}".format( name=name, dtype=self.dtype))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_method(cls, op, coerce_to_dtype=True): """ A class method that returns a method that will correspond to an operator for an ExtensionArray subclass, b...
def _binop(self, other): def convert_values(param): if isinstance(param, ExtensionArray) or is_list_like(param): ovalues = param else: # Assume its an object ovalues = [param] * len(self) return ovalues ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ea_passthrough(array_method): """ Make an alias for a method of the underlying ExtensionArray. Parameters array_method : method on an Array class Returns ---...
def method(self, *args, **kwargs): return array_method(self._data, *args, **kwargs) method.__name__ = array_method.__name__ method.__doc__ = array_method.__doc__ return method
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_comparison_method(cls, op): """ Create a comparison method that dispatches to ``cls.values``. """
def wrapper(self, other): if isinstance(other, ABCSeries): # the arrays defer to Series for comparison ops but the indexes # don't, so we have to unwrap here. other = other._values result = op(self._data, maybe_unwrap_index(other)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _join_i8_wrapper(joinf, dtype, with_indexers=True): """ Create the join wrapper methods. """
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin @staticmethod def wrapper(left, right): if isinstance(left, (np.ndarray, ABCIndex, ABCSeries, DatetimeLikeArrayMixin)): left = left.view('i8') if isinstan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_values(self, return_indexer=False, ascending=True): """ Return sorted copy of Index. """
if return_indexer: _as = self.argsort() if not ascending: _as = _as[::-1] sorted_index = self.take(_as) return sorted_index, _as else: sorted_values = np.sort(self._ndarray_values) attribs = self._get_attributes_dic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(self, axis=None, skipna=True, *args, **kwargs): """ Return the minimum value of the Index or minimum along an axis. See Also -------- numpy.ndarray.min S...
nv.validate_min(args, kwargs) nv.validate_minmax_axis(axis) if not len(self): return self._na_value i8 = self.asi8 try: # quick check if len(i8) and self.is_monotonic: if i8[0] != iNaT: return self._box_fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argmin(self, axis=None, skipna=True, *args, **kwargs): """ Returns the indices of the minimum values along an axis. See `numpy.ndarray.argmin` for more infor...
nv.validate_argmin(args, kwargs) nv.validate_minmax_axis(axis) i8 = self.asi8 if self.hasnans: mask = self._isnan if mask.all() or not skipna: return -1 i8 = i8.copy() i8[mask] = np.iinfo('int64').max return i8.arg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max(self, axis=None, skipna=True, *args, **kwargs): """ Return the maximum value of the Index or maximum along an axis. See Also -------- numpy.ndarray.max S...
nv.validate_max(args, kwargs) nv.validate_minmax_axis(axis) if not len(self): return self._na_value i8 = self.asi8 try: # quick check if len(i8) and self.is_monotonic: if i8[-1] != iNaT: return self._box_f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def argmax(self, axis=None, skipna=True, *args, **kwargs): """ Returns the indices of the maximum values along an axis. See `numpy.ndarray.argmax` for more infor...
nv.validate_argmax(args, kwargs) nv.validate_minmax_axis(axis) i8 = self.asi8 if self.hasnans: mask = self._isnan if mask.all() or not skipna: return -1 i8 = i8.copy() i8[mask] = 0 return i8.argmax()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_scalar_indexer(self, key, kind=None): """ We don't allow integer or float indexing on datetime-like when using loc. Parameters key : label of the sl...
assert kind in ['ix', 'loc', 'getitem', 'iloc', None] # we don't allow integer/float indexing for loc # we don't allow float indexing for ix/getitem if is_scalar(key): is_int = is_integer(key) is_flt = is_float(key) if kind in ['loc'] and (is_int or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isin(self, values): """ Compute boolean array of whether each index value is found in the passed set of values. Parameters values : set or sequence of values...
if not isinstance(values, type(self)): try: values = type(self)(values) except ValueError: return self.astype(object).isin(values) return algorithms.isin(self.asi8, values.asi8)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _concat_same_dtype(self, to_concat, name): """ Concatenate to_concat which has the same class. """
attribs = self._get_attributes_dict() attribs['name'] = name # do not pass tz to set because tzlocal cannot be hashed if len({str(x.dtype) for x in to_concat}) != 1: raise ValueError('to_concat must have the same tz') new_data = type(self._values)._concat_same_type(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shift(self, periods, freq=None): """ Shift index by desired number of time frequency increments. This method is for shifting the values of datetime-like inde...
result = self._data._time_shift(periods, freq=freq) return type(self)(result, name=self.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _single_replace(self, to_replace, method, inplace, limit): """ Replaces values in a Series using the fill method specified when no replacement value is given...
if self.ndim != 1: raise TypeError('cannot replace {0} with method {1} on a {2}' .format(to_replace, method, type(self).__name__)) orig_dtype = self.dtype result = self if inplace else self.copy() fill_f = missing.get_fill_func(method) mask = missing.mask_missing(r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _doc_parms(cls): """Return a tuple of the doc parms."""
axis_descr = "{%s}" % ', '.join("{0} ({1})".format(a, i) for i, a in enumerate(cls._AXIS_ORDERS)) name = (cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else 'scalar') name2 = cls.__name__ return axis_descr, name, name2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_mgr(self, mgr, axes=None, dtype=None, copy=False): """ passed a manager and a axes dict """
for a, axe in axes.items(): if axe is not None: mgr = mgr.reindex_axis(axe, axis=self._get_block_manager_axis(a), copy=False) # make a copy if explicitly requested if copy: mgr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_dtype(self, dtype): """ validate the passed dtype """
if dtype is not None: dtype = pandas_dtype(dtype) # a compound dtype if dtype.kind == 'V': raise NotImplementedError("compound dtypes are not implemented" " in the {0} constructor" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None, slicers=None, axes_are_reversed=False, build_axes=True, ns=None, docs=None): """Provide ...
cls._AXIS_ORDERS = axes cls._AXIS_NUMBERS = {a: i for i, a in enumerate(axes)} cls._AXIS_LEN = len(axes) cls._AXIS_ALIASES = aliases or dict() cls._AXIS_IALIASES = {v: k for k, v in cls._AXIS_ALIASES.items()} cls._AXIS_NAMES = dict(enumerate(axes)) cls._AXIS_SLI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _construct_axes_dict_from(self, axes, **kwargs): """Return an axes dictionary for the passed axes."""
d = {a: ax for a, ax in zip(self._AXIS_ORDERS, axes)} d.update(kwargs) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_block_manager_axis(cls, axis): """Map the axis to the block_manager axis."""
axis = cls._get_axis_number(axis) if cls._AXIS_REVERSED: m = cls._AXIS_LEN - 1 return m - axis return axis
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_space_character_free_column_resolvers(self): """Return the space character free column resolvers of a dataframe. Column names with spaces are 'cleaned u...
from pandas.core.computation.common import _remove_spaces_column_name return {_remove_spaces_column_name(k): v for k, v in self.iteritems()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shape(self): """ Return a tuple of axis dimensions """
return tuple(len(self._get_axis(a)) for a in self._AXIS_ORDERS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swapaxes(self, axis1, axis2, copy=True): """ Interchange axes and swap values axes appropriately. Returns ------- y : same as input """
i = self._get_axis_number(axis1) j = self._get_axis_number(axis2) if i == j: if copy: return self.copy() return self mapping = {i: j, j: i} new_axes = (self._get_axis(mapping.get(k, k)) for k in range(self._AXIS_LEN)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self, item): """ Return item and drop from frame. Raise KeyError if not found. Parameters item : str Label of column to be popped. Returns ------- Series...
result = self[item] del self[item] try: result._reset_cacher() except AttributeError: pass return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def squeeze(self, axis=None): """ Squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrame...
axis = (self._AXIS_NAMES if axis is None else (self._get_axis_number(axis),)) try: return self.iloc[ tuple(0 if i in axis and len(a) == 1 else slice(None) for i, a in enumerate(self.axes))] except Exception: return se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swaplevel(self, i=-2, j=-1, axis=0): """ Swap levels i and j in a MultiIndex on a particular axis Parameters i, j : int, str (can be mixed) Level of index to...
axis = self._get_axis_number(axis) result = self.copy() labels = result._data.axes[axis] result._data.set_axis(axis, labels.swaplevel(i, j)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_axis(self, mapper=sentinel, **kwargs): """ Set the name of the axis for the index or columns. Parameters mapper : scalar, list-like, optional Value to...
axes, kwargs = self._construct_axes_from_arguments( (), kwargs, sentinel=sentinel) copy = kwargs.pop('copy', True) inplace = kwargs.pop('inplace', False) axis = kwargs.pop('axis', 0) if axis is not None: axis = self._get_axis_number(axis) if kwar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def equals(self, other): """ Test whether two objects contain the same elements. This function allows two Series or DataFrames to be compared against each other ...
if not isinstance(other, self._constructor): return False return self._data.equals(other._data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bool(self): """ Return the bool of a single element PandasObject. This must be a boolean scalar value, either True or False. Raise a ValueError if the Pandas...
v = self.squeeze() if isinstance(v, (bool, np.bool_)): return bool(v) elif is_scalar(v): raise ValueError("bool cannot act on a non-boolean single element " "{0}".format(self.__class__.__name__)) self.__nonzero__()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_level_reference(self, key, axis=0): """ Test whether a key is a level reference for a given axis. To be considered a level reference, `key` must be a str...
axis = self._get_axis_number(axis) if self.ndim > 2: raise NotImplementedError( "_is_level_reference is not implemented for {type}" .format(type=type(self))) return (key is not None and is_hashable(key) and key in sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_label_reference(self, key, axis=0): """ Test whether a key is a label reference for a given axis. To be considered a label reference, `key` must be a str...
if self.ndim > 2: raise NotImplementedError( "_is_label_reference is not implemented for {type}" .format(type=type(self))) axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) return (key is not ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_label_or_level_reference(self, key, axis=0): """ Test whether a key is a label or level reference for a given axis. To be considered either a label or a ...
if self.ndim > 2: raise NotImplementedError( "_is_label_or_level_reference is not implemented for {type}" .format(type=type(self))) return (self._is_level_reference(key, axis=axis) or self._is_label_reference(key, axis=axis))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_label_or_level_ambiguity(self, key, axis=0): """ Check whether `key` is ambiguous. By ambiguous, we mean that it matches both a level of the input `ax...
if self.ndim > 2: raise NotImplementedError( "_check_label_or_level_ambiguity is not implemented for {type}" .format(type=type(self))) axis = self._get_axis_number(axis) other_axes = (ax for ax in range(self._AXIS_LEN) if ax != axis) if (key...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_label_or_level_values(self, key, axis=0): """ Return a 1-D array of values associated with `key`, a label or level from the given `axis`. Retrieval logi...
if self.ndim > 2: raise NotImplementedError( "_get_label_or_level_values is not implemented for {type}" .format(type=type(self))) axis = self._get_axis_number(axis) other_axes = [ax for ax in range(self._AXIS_LEN) if ax != axis] if self._is_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def empty(self): """ Indicator whether DataFrame is empty. True if DataFrame is entirely empty (no items), meaning any of the axes are of length 0. Returns -----...
return any(len(self._get_axis(a)) == 0 for a in self._AXIS_ORDERS)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _repr_data_resource_(self): """ Not a real Jupyter special repr method, but we use the same naming convention. """
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_pairs_hook=collections.OrderedDict) return payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, compr...
from pandas.io import json if date_format is None and orient == 'table': date_format = 'iso' elif date_format is None: date_format = 'epoch' return json.to_json(path_or_buf=path_or_buf, obj=self, orient=orient, date_format=date_format...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_hdf(self, path_or_buf, key, **kwargs): """ Write the contained data to an HDF5 file using HDFStore. Hierarchical Data Format (HDF) is self-describing, all...
from pandas.io import pytables return pytables.to_hdf(path_or_buf, key, self, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs): """ Serialize object to input file path using msgpack format. THIS IS AN EXPERIMENTAL LIBRARY...
from pandas.io import packers return packers.to_msgpack(path_or_buf, self, encoding=encoding, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_clipboard(self, excel=True, sep=None, **kwargs): r""" Copy object to the system clipboard. Write a text representation of object to the system clipboard. ...
from pandas.io import clipboards clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_xarray(self): """ Return an xarray object from the pandas object. Returns ------- xarray.DataArray or xarray.Dataset Data in the pandas structure converte...
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" "conda install xarray\n" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=T...
# Get defaults from the pandas config if self.ndim == 1: self = self.to_frame() if longtable is None: longtable = config.get_option("display.latex.longtable") if escape is None: escape = config.get_option("display.latex.escape") if multicolumn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_indexer(cls, name, indexer): """Create an indexer like _name in the class."""
if getattr(cls, name, None) is None: _indexer = functools.partial(indexer, name) setattr(cls, name, property(_indexer, doc=indexer.__doc__))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_item_cache(self, item): """Return the cached item, item represents a label indexer."""
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_as_cached(item, self) # for a chain res._is_copy = self._is_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_as_cached(self, item, cacher): """Set the _cacher attribute on the calling object with a weakref to cacher. """
self._cacher = (item, weakref.ref(cacher))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _iget_item_cache(self, item): """Return the cached item, item represents a positional indexer."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _maybe_update_cacher(self, clear=False, verify_is_copy=True): """ See if we need to update our parent cacher if clear, then clear our cache. Parameters clear...
cacher = getattr(self, '_cacher', None) if cacher is not None: ref = cacher[1]() # we are trying to reference a dead referant, hence # a copy if ref is None: del self._cacher else: try: ref...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _slice(self, slobj, axis=0, kind=None): """ Construct a slice of this container. kind parameter is maintained for compatibility with Series slicing. """
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 a single-dtyped view slicable case is_copy = axis != 0 or result._is_view result....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_is_chained_assignment_possible(self): """ Check if we are a view, have a cacher, and are of mixed type. If so, then force a setitem_copy check. Should...
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', force=True) return True elif self._is_copy: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, crit, axis=0): """ Return data corresponding to axis labels matching criteria. .. deprecated:: 0.21.0 Use df.loc[df.index.map(crit)] to select v...
warnings.warn("'select' is deprecated and will be removed in a " "future release. You can use " ".loc[labels.map(crit)] as a replacement", FutureWarning, stacklevel=2) axis = self._get_axis_number(axis) axis_name = self._get_axi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reindex_like(self, other, method=None, copy=True, limit=None, tolerance=None): """ Return an object with matching indices as other object. Conform the object...
d = other._construct_axes_dict(axes=self._AXIS_ORDERS, method=method, copy=copy, limit=limit, tolerance=tolerance) return self.reindex(**d)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _drop_axis(self, labels, axis, level=None, errors='raise'): """ Drop labels from specified axis. Used in the ``drop`` method internally. Parameters labels : ...
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: if not isinstance(axis, MultiIndex): raise AssertionError('axis must be a MultiIndex') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_inplace(self, result, verify_is_copy=True): """ Replace self internals with result. Parameters verify_is_copy : boolean, default True provide is_copy...
# 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 = getattr(result, '_data', result) self._maybe_update_cacher(verify_is_copy=verify_is_copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_prefix(self, prefix): """ Prefix labels with string `prefix`. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. Par...
f = functools.partial('{prefix}{}'.format, prefix=prefix) mapper = {self._info_axis_name: f} return self.rename(**mapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_suffix(self, suffix): """ Suffix labels with string `suffix`. For Series, the row labels are suffixed. For DataFrame, the column labels are suffixed. Par...
f = functools.partial('{}{suffix}'.format, suffix=suffix) mapper = {self._info_axis_name: f} return self.rename(**mapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_values(self, by=None, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): """ Sort by the values along either axis. Parameters...
raise NotImplementedError("sort_values has not been implemented " "on Panel or Panel4D objects.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy): """Perform the reindex for all the axes."""
obj = self for a in self._AXIS_ORDERS: labels = axes[a] if labels is None: continue ax = self._get_axis(a) new_index, indexer = ax.reindex(labels, level=level, limit=limit, tolerance=tolerance, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _needs_reindex_multi(self, axes, method, level): """Check if we do need a multi reindex."""
return ((com.count_not_none(*axes.values()) == self._AXIS_LEN) and method is None and level is None and not self._is_mixed_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reindex_with_indexers(self, reindexers, fill_value=None, copy=False, allow_dups=False): """allow_dups indicates an internal call here """
# reindex doing multiple operations on different axes if indicated new_data = self._data for axis in sorted(reindexers.keys()): index, indexer = reindexers[axis] baxis = self._get_block_manager_axis(axis) if index is None: continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, items=None, like=None, regex=None, axis=None): """ Subset rows or columns of dataframe according to labels in the specified index. Note that thi...
import re nkw = com.count_not_none(items, like, regex) if nkw > 1: raise TypeError('Keyword arguments `items`, `like`, or `regex` ' 'are mutually exclusive') if axis is None: axis = self._info_axis_name labels = self._get_axi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample(self, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None): """ Return a random sample of items from an axis of object. You c...
if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) axis_length = self.shape[axis] # Process random_state argument rs = com.random_state(random_state) # Check weights for compliance if weights is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dir_additions(self): """ add the string-like attributes from the info_axis. If info_axis is a MultiIndex, it's first level values are used. """
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _consolidate_inplace(self): """Consolidate data in place and return None"""
def f(): self._data = self._data.consolidate() self._protect_consolidate(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_inplace_setting(self, value): """ check whether we allow in-place setting with this type of 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 except Exception: pass raise TypeError('C...