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 as_matrix(self, columns=None): """ Convert the frame to its Numpy-array representation. .. deprecated:: 0.23.0 Use :meth:`DataFrame.values` instead. Paramete...
warnings.warn("Method .as_matrix will be removed in a future version. " "Use .values instead.", FutureWarning, stacklevel=2) self._consolidate_inplace() return self._data.as_array(transpose=self._AXIS_REVERSED, items=columns)
<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(self): """ Return a Numpy representation of the DataFrame. .. warning:: We recommend using :meth:`DataFrame.to_numpy` instead. Only the values in the ...
self._consolidate_inplace() return self._data.as_array(transpose=self._AXIS_REVERSED)
<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_ftype_counts(self): """ Return counts of unique ftypes in this object. .. deprecated:: 0.23.0 This is useful for SparseDataFrame or for DataFrames contai...
warnings.warn("get_ftype_counts is deprecated and will " "be removed in a future version", FutureWarning, stacklevel=2) from pandas import Series return Series(self._data.get_ftype_counts())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dtypes(self): """ Return the dtypes in the DataFrame. This returns a Series with the data type of each column. The result's index is the original DataFrame's...
from pandas import Series return Series(self._data.get_dtypes(), index=self._info_axis, dtype=np.object_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_blocks(self, copy=True): """ Convert the frame to a dict of dtype -> Constructor Types that each has a homogeneous dtype. .. deprecated:: 0.21.0 NOTE: the...
warnings.warn("as_blocks is deprecated and will " "be removed in a future version", FutureWarning, stacklevel=2) return self._to_dict_of_blocks(copy=copy)
<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_dict_of_blocks(self, copy=True): """ Return a dict of dtype -> Constructor Types that each is a homogeneous dtype. Internal ONLY """
return {k: self._constructor(v).__finalize__(self) for k, v, in self._data.to_dict(copy=copy).items()}
<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, errors='raise', **kwargs): """ Cast a pandas object to a specified dtype ``dtype``. Parameters dtype : data type, or dict of c...
if is_dict_like(dtype): if self.ndim == 1: # i.e. Series if len(dtype) > 1 or self.name not in dtype: raise KeyError('Only the Series name can be used for ' 'the key in Series dtype mappings.') new_type = 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 copy(self, deep=True): """ Make a copy of this object's indices and data. When ``deep=True`` (default), a new object will be created with a copy of the calli...
data = self._data.copy(deep=deep) return self._constructor(data).__finalize__(self)
<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(self, datetime=False, numeric=False, timedelta=False, coerce=False, copy=True): """ Attempt to infer better dtype for object columns Parameters date...
return self._constructor( self._data.convert(datetime=datetime, numeric=numeric, timedelta=timedelta, coerce=coerce, copy=copy)).__finalize__(self)
<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_objects(self, convert_dates=True, convert_numeric=False, convert_timedeltas=True, copy=True): """ Attempt to infer better dtype for object columns. ....
msg = ("convert_objects is deprecated. To re-infer data dtypes for " "object columns, use {klass}.infer_objects()\nFor all " "other conversions use the data-type specific converters " "pd.to_datetime, pd.to_timedelta and pd.to_numeric." ).format(klas...
<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_objects(self): """ Attempt to infer better dtypes for object columns. Attempts soft conversion of object-dtyped columns, leaving non-object and unconve...
# numeric=False necessary to only soft convert; # python objects will still be converted to # native numpy numeric types return self._constructor( self._data.convert(datetime=True, numeric=False, timedelta=True, coerce=False, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip_upper(self, threshold, axis=None, inplace=False): """ Trim values above a given threshold. .. deprecated:: 0.24.0 Use clip(upper=threshold) instead. Ele...
warnings.warn('clip_upper(threshold) is deprecated, ' 'use clip(upper=threshold) instead', FutureWarning, stacklevel=2) return self._clip_with_one_bound(threshold, method=self.le, axis=axis, inplace=inplace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip_lower(self, threshold, axis=None, inplace=False): """ Trim values below a given threshold. .. deprecated:: 0.24.0 Use clip(lower=threshold) instead. Ele...
warnings.warn('clip_lower(threshold) is deprecated, ' 'use clip(lower=threshold) instead', FutureWarning, stacklevel=2) return self._clip_with_one_bound(threshold, method=self.ge, axis=axis, inplace=inplace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs): """ Group DataFrame or Series...
from pandas.core.groupby.groupby import groupby if level is None and by is None: raise TypeError("You have to supply one of 'by' and 'level'") axis = self._get_axis_number(axis) return groupby(self, by=by, axis=axis, level=level, as_index=as_index, so...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asfreq(self, freq, method=None, how=None, normalize=False, fill_value=None): """ Convert TimeSeries to specified frequency. Optionally provide filling method...
from pandas.core.resample import asfreq return asfreq(self, freq, method=method, how=how, normalize=normalize, fill_value=fill_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(self, rule, how=None, axis=0, fill_method=None, closed=None, label=None, convention='start', kind=None, loffset=None, limit=None, base=0, on=None, le...
from pandas.core.resample import (resample, _maybe_process_deprecations) axis = self._get_axis_number(axis) r = resample(self, freq=rule, label=label, closed=closed, axis=axis, kind=kind, loffset=loffset, conve...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first(self, offset): """ Convenience method for subsetting initial periods of time series data based on a date offset. Parameters offset : string, DateOffset...
if not isinstance(self.index, DatetimeIndex): raise TypeError("'first' only supports a DatetimeIndex index") if len(self.index) == 0: return self offset = to_offset(offset) end_date = end = self.index[0] + offset # Tick-like, e.g. 3 weeks if no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def last(self, offset): """ Convenience method for subsetting final periods of time series data based on a date offset. Parameters offset : string, DateOffset, d...
if not isinstance(self.index, DatetimeIndex): raise TypeError("'last' only supports a DatetimeIndex index") if len(self.index) == 0: return self offset = to_offset(offset) start_date = self.index[-1] - offset start = self.index.searchsorted(start_date,...
<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_shift(self, periods=1, axis=0): """ Equivalent to `shift` without copying data. The shifted data will not include the dropped periods and the shifted a...
if periods == 0: return self if periods > 0: vslicer = slice(None, -periods) islicer = slice(periods, None) else: vslicer = slice(-periods, None) islicer = slice(None, periods) new_obj = self._slice(vslicer, 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 tshift(self, periods=1, freq=None, axis=0): """ Shift the time index, using the index's frequency if available. Parameters periods : int Number of periods to...
index = self._get_axis(axis) if freq is None: freq = getattr(index, 'freq', None) if freq is None: freq = getattr(index, 'inferred_freq', None) if freq is None: msg = 'Freq was not given and was not set in the index' raise ValueError(ms...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate(self, before=None, after=None, axis=None, copy=True): """ Truncate a Series or DataFrame before and after some index value. This is a useful shortha...
if axis is None: axis = self._stat_axis_number axis = self._get_axis_number(axis) ax = self._get_axis(axis) # GH 17935 # Check that index is sorted if not ax.is_monotonic_increasing and not ax.is_monotonic_decreasing: raise ValueError("truncate ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tz_convert(self, tz, axis=0, level=None, copy=True): """ Convert tz-aware axis to target time zone. Parameters tz : string or pytz.timezone object axis : the...
axis = self._get_axis_number(axis) ax = self._get_axis(axis) def _tz_convert(ax, tz): if not hasattr(ax, 'tz_convert'): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError('%s is not a valid DatetimeIndex 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 tz_localize(self, tz, axis=0, level=None, copy=True, ambiguous='raise', nonexistent='raise'): """ Localize tz-naive index of a Series or DataFrame to target ...
nonexistent_options = ('raise', 'NaT', 'shift_forward', 'shift_backward') if nonexistent not in nonexistent_options and not isinstance( nonexistent, timedelta): raise ValueError("The nonexistent argument must be one of 'raise'," ...
<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_series_or_dataframe_operations(cls): """ Add the series or dataframe only operations to the cls; evaluate the doc strings again. """
from pandas.core import window as rwindow @Appender(rwindow.rolling.__doc__) def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None): axis = self._get_axis_number(axis) return rwindow.rolling(self, wind...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_valid_index(self, how): """ Retrieves the index of the first valid value. Parameters how : {'first', 'last'} Use this parameter to change between the f...
assert how in ['first', 'last'] if len(self) == 0: # early stop return None is_valid = ~self.isna() if self.ndim == 2: is_valid = is_valid.any(1) # reduce axis 1 if how == 'first': idxpos = is_valid.values[::].argmax() if how == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _reset_cache(self, key=None): """ Reset cached properties. If ``key`` is passed, only clears that key. """
if getattr(self, '_cache', None) is None: return if key is None: self._cache.clear() else: self._cache.pop(key, 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 _shallow_copy(self, obj=None, obj_type=None, **kwargs): """ return a new object with the replacement attributes """
if obj is None: obj = self._selected_obj.copy() if obj_type is None: obj_type = self._constructor if isinstance(obj, obj_type): obj = obj.obj for attr in self._attributes: if attr not in kwargs: kwargs[attr] = getattr(self,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def itemsize(self): """ Return the size of the dtype of the item of the underlying data. .. deprecated:: 0.23.0 """
warnings.warn("{obj}.itemsize is deprecated and will be removed " "in a future version".format(obj=type(self).__name__), FutureWarning, stacklevel=2) return self._ndarray_values.itemsize
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base(self): """ Return the base object if the memory of the underlying data is shared. .. deprecated:: 0.23.0 """
warnings.warn("{obj}.base is deprecated and will be removed " "in a future version".format(obj=type(self).__name__), FutureWarning, stacklevel=2) return self.values.base
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array(self) -> ExtensionArray: """ The ExtensionArray of the data backing this Series or Index. .. versionadded:: 0.24.0 Returns ------- ExtensionArray An Ext...
result = self._values if is_datetime64_ns_dtype(result.dtype): from pandas.arrays import DatetimeArray result = DatetimeArray(result) elif is_timedelta64_ns_dtype(result.dtype): from pandas.arrays import TimedeltaArray result = TimedeltaArray(res...
<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_numpy(self, dtype=None, copy=False): """ A NumPy ndarray representing the values in this Series or Index. .. versionadded:: 0.24.0 Parameters dtype : str ...
if is_datetime64tz_dtype(self.dtype) and dtype is None: # note: this is going to change very soon. # I have a WIP PR making this unnecessary, but it's # a bit out of scope for the DatetimeArray PR. dtype = "object" result = np.asarray(self._values, 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 _ndarray_values(self) -> np.ndarray: """ The data as an ndarray, possibly losing information. The expectation is that this is cheap to compute, and is primari...
if is_extension_array_dtype(self): return self.array._ndarray_values return self.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 max(self, axis=None, skipna=True): """ Return the maximum value of the Index. Parameters axis : int, optional For compatibility with NumPy. Only 0 or None ar...
nv.validate_minmax_axis(axis) return nanops.nanmax(self._values, skipna=skipna)
<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): """ Return an ndarray of the maximum argument indexer. Parameters axis : {None} Dummy argument for consistency with Ser...
nv.validate_minmax_axis(axis) return nanops.nanargmax(self._values, skipna=skipna)
<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): """ Return the minimum value of the Index. Parameters axis : {None} Dummy argument for consistency with Series skipna : bo...
nv.validate_minmax_axis(axis) return nanops.nanmin(self._values, skipna=skipna)
<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): """ Return a ndarray of the minimum argument indexer. Parameters axis : {None} Dummy argument for consistency with Seri...
nv.validate_minmax_axis(axis) return nanops.nanargmin(self._values, skipna=skipna)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tolist(self): """ Return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp...
if is_datetimelike(self._values): return [com.maybe_box_datetimelike(x) for x in self._values] elif is_extension_array_dtype(self._values): return list(self._values) else: return self._values.tolist()
<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, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds): """ perform the reduction type operation if we can """
func = getattr(self, name, None) if func is None: raise TypeError("{klass} cannot perform the operation {op}".format( klass=self.__class__.__name__, op=name)) return func(skipna=skipna, **kwds)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nunique(self, dropna=True): """ Return number of unique elements in the object. Excludes NA values by default. Parameters dropna : bool, default True Don't i...
uniqs = self.unique() n = len(uniqs) if dropna and isna(uniqs).any(): n -= 1 return 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 memory_usage(self, deep=False): """ Memory usage of the values Parameters deep : bool Introspect the data deeply, interrogate `object` dtypes for system-leve...
if hasattr(self.array, 'memory_usage'): return self.array.memory_usage(deep=deep) v = self.array.nbytes if deep and is_object_dtype(self) and not PYPY: v += lib.memory_usage_of_objects(self.array) return v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stringify_path(filepath_or_buffer): """Attempt to convert a path-like object to a string. Parameters filepath_or_buffer : object to be converted Returns ---...
try: import pathlib _PATHLIB_INSTALLED = True except ImportError: _PATHLIB_INSTALLED = False try: from py.path import local as LocalPath _PY_PATH_INSTALLED = True except ImportError: _PY_PATH_INSTALLED = False if hasattr(filepath_or_buffer, '__fspat...
<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_filepath_or_buffer(filepath_or_buffer, encoding=None, compression=None, mode=None): """ If the filepath_or_buffer is a url, translate and return the buff...
filepath_or_buffer = _stringify_path(filepath_or_buffer) if _is_url(filepath_or_buffer): req = urlopen(filepath_or_buffer) content_encoding = req.headers.get('Content-Encoding', None) if content_encoding == 'gzip': # Override compression based on Content-Encoding header ...
<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_compression(filepath_or_buffer, compression): """ Get the compression method for filepath_or_buffer. If compression='infer', the inferred compression ...
# No compression has been explicitly specified if compression is None: return None # Infer compression if compression == 'infer': # Convert all path types (e.g. pathlib.Path) to strings filepath_or_buffer = _stringify_path(filepath_or_buffer) if not isinstance(filepath...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _td_array_cmp(cls, op): """ Wrap comparison operations to convert timedelta-like to timedelta64 """
opname = '__{name}__'.format(name=op.__name__) nat_result = opname == '__ne__' def wrapper(self, other): if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): return NotImplemented if _is_convertible_to_td(other) or other is NaT: try: othe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_writer(klass): """ Add engine to the excel writer registry.io.excel. You must use this method to integrate with ``to_excel``. Parameters klass : Exc...
if not callable(klass): raise ValueError("Can only register callables as engines") engine_name = klass.engine _writers[engine_name] = klass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _excel2num(x): """ Convert Excel column name like 'AB' to 0-based column index. Parameters x : str The Excel column name to convert to a 0-based column index...
index = 0 for c in x.upper().strip(): cp = ord(c) if cp < ord("A") or cp > ord("Z"): raise ValueError("Invalid column name: {x}".format(x=x)) index = index * 26 + cp - ord("A") + 1 return index - 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _range2cols(areas): """ Convert comma separated list of column names and ranges to indices. Parameters areas : str A string containing a sequence of column r...
cols = [] for rng in areas.split(","): if ":" in rng: rng = rng.split(":") cols.extend(lrange(_excel2num(rng[0]), _excel2num(rng[1]) + 1)) else: cols.append(_excel2num(rng)) return cols
<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_convert_usecols(usecols): """ Convert `usecols` into a compatible format for parsing in `parsers.py`. Parameters usecols : object The use-columns obje...
if usecols is None: return usecols if is_integer(usecols): warnings.warn(("Passing in an integer for `usecols` has been " "deprecated. Please pass in a list of int from " "0 to `usecols` inclusive instead."), FutureWarning, 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 _fill_mi_header(row, control_row): """Forward fill blank entries in row but only inside the same parent index. Used for creating headers in Multiindex. Param...
last = row[0] for i in range(1, len(row)): if not control_row[i]: last = row[i] if row[i] == '' or row[i] is None: row[i] = last else: control_row[i] = False last = row[i] return row, control_row
<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_header_name(row, index_col): """ Pop the header name for MultiIndex parsing. Parameters row : list The data row to parse for the header name. index_col ...
# Pop out header name and fill w/blank. i = index_col if not is_list_like(index_col) else max(index_col) header_name = row[i] header_name = None if header_name == "" else header_name return header_name, row[:i] + [''] + row[i + 1:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_scope(level, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs): """Ensure that we are grabbing the correct scope."""
return Scope(level + 1, global_dict=global_dict, local_dict=local_dict, resolvers=resolvers, target=target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replacer(x): """Replace a number with its hexadecimal representation. Used to tag temporary variables with their calling scope's id. """
# get the hex repr of the binary char and remove 0x and pad by pad_size # zeros try: hexin = ord(x) except TypeError: # bytes literals masquerade as ints when iterating in py3 hexin = x return hex(hexin)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raw_hex_id(obj): """Return the padded hexadecimal id of ``obj``."""
# interpret as a pointer since that's what really what id returns packed = struct.pack('@P', id(obj)) return ''.join(map(_replacer, packed))
<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_pretty_string(obj): """Return a prettier version of obj Parameters obj : object Object to pretty print Returns ------- s : str Pretty print object repr ...
sio = StringIO() pprint.pprint(obj, stream=sio) return sio.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve(self, key, is_local): """Resolve a variable name in a possibly local context Parameters key : str A variable name is_local : bool Flag indicating whe...
try: # only look for locals in outer scope if is_local: return self.scope[key] # not a local variable so check in resolvers if we have them if self.has_resolvers: return self.resolvers[key] # if we're here that means ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def swapkey(self, old_key, new_key, new_value=None): """Replace a variable name, with a potentially new value. Parameters old_key : str Current variable name to ...
if self.has_resolvers: maps = self.resolvers.maps + self.scope.maps else: maps = self.scope.maps maps.append(self.temps) for mapping in maps: if old_key in mapping: mapping[new_key] = new_value return
<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_vars(self, stack, scopes): """Get specifically scoped variables from a list of stack frames. Parameters stack : list A list of stack frames as returned ...
variables = itertools.product(scopes, stack) for scope, (frame, _, _, _, _, _) in variables: try: d = getattr(frame, 'f_' + scope) self.scope = self.scope.new_child(d) finally: # won't remove it, but DECREF it # in ...
<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(self, level): """Update the current scope by going back `level` levels. Parameters level : int or None, optional, default None """
sl = level + 1 # add sl frames to the scope starting with the # most distant and overwriting with more current # makes sure that we can capture variable scope stack = inspect.stack() try: self._get_vars(stack[:sl], scopes=['locals']) finally: ...
<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_tmp(self, value): """Add a temporary variable to the scope. Parameters value : object An arbitrary object to be assigned to a temporary variable. Returns...
name = '{name}_{num}_{hex_id}'.format(name=type(value).__name__, num=self.ntemps, hex_id=_raw_hex_id(self)) # add to inner most scope assert name not in self.temps self.temps[name] = value ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_scope(self): """Return the full scope for use with passing to engines transparently as a mapping. Returns ------- vars : DeepChainMap All variables in t...
maps = [self.temps] + self.resolvers.maps + self.scope.maps return DeepChainMap(*maps)
<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_sas(filepath_or_buffer, format=None, index=None, encoding=None, chunksize=None, iterator=False): """ Read SAS files stored as either XPORT or SAS7BDAT f...
if format is None: buffer_error_msg = ("If this is a buffer object rather " "than a string name, you must specify " "a format string") filepath_or_buffer = _stringify_path(filepath_or_buffer) if not isinstance(filepath_or_buffer, str):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _coerce_method(converter): """ Install the scalar coercion methods. """
def wrapper(self): if len(self) == 1: return converter(self.iloc[0]) raise TypeError("cannot convert the series to " "{0}".format(str(converter))) wrapper.__name__ = "__{name}__".format(name=converter.__name__) return wrapper
<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_dict(self, data, index=None, dtype=None): """ Derive the "_data" and "index" attributes of a new Series from a dictionary input. Parameters data : dict...
# Looking for NaN in dict doesn't work ({np.nan : 1}[float('nan')] # raises KeyError), so we iterate the entire dict, and align if data: keys, values = zip(*data.items()) values = list(values) elif index is not None: # fastpath for Series(data=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 from_array(cls, arr, index=None, name=None, dtype=None, copy=False, fastpath=False): """ Construct Series from array. .. deprecated :: 0.23.0 Use pd.Series(....
warnings.warn("'from_array' is deprecated and will be removed in a " "future version. Please use the pd.Series(..) " "constructor instead.", FutureWarning, stacklevel=2) if isinstance(arr, ABCSparseArray): from pandas.core.sparse.series import Spa...
<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_axis(self, axis, labels, fastpath=False): """ Override generic, we want to set the _typ here. """
if not fastpath: labels = ensure_index(labels) is_all_dates = labels.is_all_dates if is_all_dates: if not isinstance(labels, (DatetimeIndex, PeriodIndex, TimedeltaIndex)): try: labels = DatetimeIndex(lab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asobject(self): """ Return object Series which contains boxed values. .. deprecated :: 0.23.0 Use ``astype(object)`` instead. *this is an internal non-public...
warnings.warn("'asobject' is deprecated. Use 'astype(object)'" " instead", FutureWarning, stacklevel=2) return self.astype(object).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 compress(self, condition, *args, **kwargs): """ Return selected slices of an array along given axis as a Series. .. deprecated:: 0.24.0 See Also -------- num...
msg = ("Series.compress(condition) is deprecated. " "Use 'Series[condition]' or " "'np.asarray(series).compress(condition)' instead.") warnings.warn(msg, FutureWarning, stacklevel=2) nv.validate_compress(args, kwargs) return self[condition]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view(self, dtype=None): """ Create a new view of the Series. This function will return a new Series with a view of the same underlying values in memory, opti...
return self._constructor(self._values.view(dtype), index=self.index).__finalize__(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ixs(self, i, axis=0): """ Return the i-th value or values in the Series by location. Parameters i : int, slice, or sequence of integers Returns ------- scal...
try: # dispatch to the values if we need values = self._values if isinstance(values, np.ndarray): return libindex.get_value_at(values, i) else: return values[i] except IndexError: raise except Exception...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def repeat(self, repeats, axis=None): """ Repeat elements of a Series. Returns a new Series where each element of the current Series is repeated consecutively a ...
nv.validate_repeat(tuple(), dict(axis=axis)) new_index = self.index.repeat(repeats) new_values = self._values.repeat(repeats) return self._constructor(new_values, index=new_index).__finalize__(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_index(self, level=None, drop=False, name=None, inplace=False): """ Generate a new DataFrame or Series with the index reset. This is useful when the ind...
inplace = validate_bool_kwarg(inplace, 'inplace') if drop: new_index = ibase.default_index(len(self)) if level is not None: if not isinstance(level, (tuple, list)): level = [level] level = [self.index._get_level_number(lev) for...
<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_string(self, buf=None, na_rep='NaN', float_format=None, header=True, index=True, length=False, dtype=False, name=False, max_rows=None): """ Render a strin...
formatter = fmt.SeriesFormatter(self, name=name, length=length, header=header, index=index, dtype=dtype, na_rep=na_rep, float_format=float_format, max...
<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_frame(self, name=None): """ Convert Series to DataFrame. Parameters name : object, default None The passed name should substitute for the series name (if ...
if name is None: df = self._constructor_expanddim(self) else: df = self._constructor_expanddim({name: self}) return df
<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_sparse(self, kind='block', fill_value=None): """ Convert Series to SparseSeries. Parameters kind : {'block', 'integer'}, default 'block' fill_value : floa...
# TODO: deprecate from pandas.core.sparse.series import SparseSeries values = SparseArray(self, kind=kind, fill_value=fill_value) return SparseSeries( values, index=self.index, name=self.name ).__finalize__(self)
<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_name(self, name, inplace=False): """ Set the Series name. Parameters name : str inplace : bool whether to modify `self` directly or return a copy """
inplace = validate_bool_kwarg(inplace, 'inplace') ser = self if inplace else self.copy() ser.name = name return ser
<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_duplicates(self, keep='first', inplace=False): """ Return Series with duplicate values removed. Parameters keep : {'first', 'last', ``False``}, default ...
return super().drop_duplicates(keep=keep, inplace=inplace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def idxmin(self, axis=0, skipna=True, *args, **kwargs): """ Return the row label of the minimum value. If multiple values equal the minimum, the first row label ...
skipna = nv.validate_argmin_with_skipna(skipna, args, kwargs) i = nanops.nanargmin(com.values_from_object(self), skipna=skipna) if i == -1: return np.nan return self.index[i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def idxmax(self, axis=0, skipna=True, *args, **kwargs): """ Return the row label of the maximum value. If multiple values equal the maximum, the first row label ...
skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs) i = nanops.nanargmax(com.values_from_object(self), skipna=skipna) if i == -1: return np.nan return self.index[i]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round(self, decimals=0, *args, **kwargs): """ Round each value in a Series to the given number of decimals. Parameters decimals : int Number of decimal place...
nv.validate_round(args, kwargs) result = com.values_from_object(self).round(decimals) result = self._constructor(result, index=self.index).__finalize__(self) 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 quantile(self, q=0.5, interpolation='linear'): """ Return value at the given quantile. Parameters q : float or array-like, default 0.5 (50% quantile) 0 <= q ...
self._check_percentile(q) # We dispatch to DataFrame so that core.internals only has to worry # about 2D cases. df = self.to_frame() result = df.quantile(q=q, interpolation=interpolation, numeric_only=False) if result.ndim == 2: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def corr(self, other, method='pearson', min_periods=None): """ Compute correlation with `other` Series, excluding missing values. Parameters other : Series Serie...
this, other = self.align(other, join='inner', copy=False) if len(this) == 0: return np.nan if method in ['pearson', 'spearman', 'kendall'] or callable(method): return nanops.nancorr(this.values, other.values, method=method, min_periods=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cov(self, other, min_periods=None): """ Compute covariance with Series, excluding missing values. Parameters other : Series Series with which to compute the ...
this, other = self.align(other, join='inner', copy=False) if len(this) == 0: return np.nan return nanops.nancov(this.values, other.values, min_periods=min_periods)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dot(self, other): """ Compute the dot product between the Series and the columns of other. This method computes the dot product between the Series and anothe...
from pandas.core.frame import DataFrame if isinstance(other, (Series, DataFrame)): common = self.index.union(other.index) if (len(common) > len(self.index) or len(common) > len(other.index)): raise ValueError('matrices are not aligned') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, to_append, ignore_index=False, verify_integrity=False): """ Concatenate two or more Series. Parameters to_append : Series or list/tuple of Serie...
from pandas.core.reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] + to_append else: to_concat = [self, to_append] return concat(to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _binop(self, other, func, level=None, fill_value=None): """ Perform generic binary operation with optional fill value. Parameters other : Series func : binar...
if not isinstance(other, Series): raise AssertionError('Other operand must be Series') new_index = self.index this = self if not self.index.equals(other.index): this, other = self.align(other, level=level, join='outer', cop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine(self, other, func, fill_value=None): """ Combine the Series with a Series or scalar according to `func`. Combine the Series and `other` using `func` ...
if fill_value is None: fill_value = na_value_for_dtype(self.dtype, compat=False) if isinstance(other, Series): # If other is a Series, result is based on union of Series, # so do this element by element new_index = self.index.union(other.index) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_first(self, other): """ Combine Series values, choosing the calling Series's values first. Parameters other : Series The value(s) to be combined with...
new_index = self.index.union(other.index) this = self.reindex(new_index, copy=False) other = other.reindex(new_index, copy=False) if is_datetimelike(this) and not is_datetimelike(other): other = to_datetime(other) return this.where(notna(this), 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 update(self, other): """ Modify Series in place using non-NA values from passed Series. Aligns on index. Parameters other : Series Examples -------- 0 4 1 5 ...
other = other.reindex_like(self) mask = notna(other) self._data = self._data.putmask(mask=mask, new=other, inplace=True) self._maybe_update_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 sort_values(self, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last'): """ Sort by the values. Sort a Series in ascending or descend...
inplace = validate_bool_kwarg(inplace, 'inplace') # Validate the axis parameter self._get_axis_number(axis) # GH 5856/5853 if inplace and self._is_cached: raise ValueError("This Series is a view of some other array, to " "sort in-place y...
<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_index(self, axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True): """ Sort Series by index labe...
# TODO: this can be combined with DataFrame.sort_index impl as # almost identical inplace = validate_bool_kwarg(inplace, 'inplace') # Validate the axis parameter self._get_axis_number(axis) index = self.index if level is not None: new_index, indexer ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nlargest(self, n=5, keep='first'): """ Return the largest `n` elements. Parameters n : int, default 5 Return this many descending sorted values. keep : {'fir...
return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nsmallest(self, n=5, keep='first'): """ Return the smallest `n` elements. Parameters n : int, default 5 Return this many ascending sorted values. keep : {'fi...
return algorithms.SelectNSeries(self, n=n, keep=keep).nsmallest()
<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, copy=True): """ Swap levels i and j in a MultiIndex. Parameters i, j : int, str (can be mixed) Level of index to be swapped. Can ...
new_index = self.index.swaplevel(i, j) return self._constructor(self._values, index=new_index, copy=copy).__finalize__(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map(self, arg, na_action=None): """ Map values of Series according to input correspondence. Used for substituting each value in a Series with another value, ...
new_values = super()._map_values( arg, na_action=na_action) return self._constructor(new_values, index=self.index).__finalize__(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, func, convert_dtype=True, args=(), **kwds): """ Invoke function on values of Series. Can be ufunc (a NumPy function that applies to the entire Se...
if len(self) == 0: return self._constructor(dtype=self.dtype, index=self.index).__finalize__(self) # dispatch to agg if isinstance(func, (list, dict)): return self.aggregate(func, *args, **kwds) # if we are a string, try to ...
<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, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds): """ Perform a reduction operation. If we have an ndarray as a valu...
delegate = self._values if axis is not None: self._get_axis_number(axis) if isinstance(delegate, Categorical): # TODO deprecate numeric_only argument for Categorical and use # skipna as well, see GH25303 return delegate._reduce(name, numeric_onl...
<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(self, index=None, **kwargs): """ Alter Series index labels or name. Function / dict values must be unique (1-to-1). Labels not contained in a dict / S...
kwargs['inplace'] = validate_bool_kwarg(kwargs.get('inplace', False), 'inplace') non_mapping = is_scalar(index) or (is_list_like(index) and not is_dict_like(index)) if non_mapping: return 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 reindex_axis(self, labels, axis=0, **kwargs): """ Conform Series to new index with optional filling logic. .. deprecated:: 0.21.0 Use ``Series.reindex`` inst...
# for compatibility with higher dims if axis != 0: raise ValueError("cannot reindex series on non-zero axis!") msg = ("'.reindex_axis' is deprecated and will be removed in a future " "version. Use '.reindex' instead.") warnings.warn(msg, FutureWarning, stackle...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memory_usage(self, index=True, deep=False): """ Return the memory usage of the Series. The memory usage can optionally include the contribution of the index ...
v = super().memory_usage(deep=deep) if index: v += self.index.memory_usage(deep=deep) return v
<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): """ Check whether `values` are contained in Series. Return a boolean Series showing whether each element in the Series matches an element...
result = algorithms.isin(self, values) return self._constructor(result, index=self.index).__finalize__(self)