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 integer_array(values, dtype=None, copy=False): """ Infer and return an integer array of the values. Parameters values : 1D list-like dtype : dtype, optional ...
values, mask = coerce_to_array(values, dtype=dtype, copy=copy) return IntegerArray(values, mask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_cast(values, dtype, copy): """ Safely cast the values to the dtype if they are equivalent, meaning floats must be equivalent to the ints. """
try: return values.astype(dtype, casting='safe', copy=copy) except TypeError: casted = values.astype(dtype, copy=copy) if (casted == values).all(): return casted raise TypeError("cannot safely cast non-equivalent {} to {}".format( values.dtype, np.dtyp...
<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_to_array(values, dtype, mask=None, copy=False): """ Coerce the input values array to numpy arrays with a mask Parameters values : 1D list-like dtype :...
# if values is integer numpy array, preserve it's dtype if dtype is None and hasattr(values, 'dtype'): if is_integer_dtype(values.dtype): dtype = values.dtype if dtype is not None: if (isinstance(dtype, str) and (dtype.startswith("Int") or dtype.startswith("UInt...
<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_from_string(cls, string): """ Construction from a string, raise a TypeError if not possible """
if string == cls.name: return cls() raise TypeError("Cannot construct a '{}' from " "'{}'".format(cls, string))
<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_to_ndarray(self): """ coerce to an ndarary of object dtype """
# TODO(jreback) make this better data = self._data.astype(object) data[self._mask] = self._na_value return 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 astype(self, dtype, copy=True): """ Cast to a NumPy array or IntegerArray with 'dtype'. Parameters dtype : str or dtype Typecode or data-type to which the ar...
# if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dtype, copy=False) return type(self)(result, mask=self._mask, copy=False) # coerce data = self._coerce_to_ndarray() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value_counts(self, dropna=True): """ Returns a Series containing counts of each category. Every category will have an entry, even those with a count of 0. Pa...
from pandas import Index, Series # compute counts on the data with no nans data = self._data[~self._mask] value_counts = Index(data).value_counts() array = value_counts.values # TODO(extension) # if we have allow Index to hold an ExtensionArray # this ...
<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_argsort(self) -> np.ndarray: """Return values for sorting. Returns ------- ndarray The transformed values should maintain the ordering between val...
data = self._data.copy() data[self._mask] = data.min() - 1 return 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 length_of_indexer(indexer, target=None): """ return the length of a single non-tuple indexer which could be a slice """
if target is not None and isinstance(indexer, slice): target_len = len(target) start = indexer.start stop = indexer.stop step = indexer.step if start is None: start = 0 elif start < 0: start += target_len if stop is None or stop > targ...
<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_to_index_sliceable(obj, key): """ if we are index sliceable, then return my slicer, otherwise return None """
idx = obj.index if isinstance(key, slice): return idx._convert_slice_indexer(key, kind='getitem') elif isinstance(key, str): # we are an actual column if obj._data.items.contains(key): return None # We might have a datetimelike string that we can translate 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 check_setitem_lengths(indexer, value, values): """ Validate that value and indexer are the same length. An special-case is allowed for when the indexer is a ...
# boolean with truth values == len of the value is ok too if isinstance(indexer, (np.ndarray, list)): if is_list_like(value) and len(indexer) != len(value): if not (isinstance(indexer, np.ndarray) and indexer.dtype == np.bool_ and len(indexer[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 convert_missing_indexer(indexer): """ reverse convert a missing indexer, which is a dict return the scalar indexer and a boolean indicating if we converted "...
if isinstance(indexer, dict): # a missing key (but not a tuple indexer) indexer = indexer['key'] if isinstance(indexer, bool): raise KeyError("cannot use a single bool to index into setitem") return indexer, True return indexer, 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 convert_from_missing_indexer_tuple(indexer, axes): """ create a filtered indexer that doesn't have any missing indexers """
def get_indexer(_i, _idx): return (axes[_i].get_loc(_idx['key']) if isinstance(_idx, dict) else _idx) return tuple(get_indexer(_i, _idx) for _i, _idx in enumerate(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 maybe_convert_indices(indices, n): """ Attempt to convert indices into valid, positive indices. If we have negative indices, translate to positive here. If w...
if isinstance(indices, list): indices = np.array(indices) if len(indices) == 0: # If list is empty, np.array will return float and cause indexing # errors. return np.empty(0, dtype=np.intp) mask = indices < 0 if mask.any(): indices = indices.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 validate_indices(indices, n): """ Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters indices : ndarray n : int l...
if len(indices): min_idx = indices.min() if min_idx < -1: msg = ("'indices' contains values less than allowed ({} < {})" .format(min_idx, -1)) raise ValueError(msg) max_idx = indices.max() if max_idx >= n: raise IndexError("ind...
<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_ix(*args): """ We likely want to take the cross-product """
ixify = True for arg in args: if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)): ixify = False if ixify: return np.ix_(*args) else: return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _non_reducing_slice(slice_): """ Ensurse that a slice doesn't reduce to a Series or Scalar. Any user-paseed `subset` should have this called on it to make su...
# default to column slice, like DataFrame # ['A', 'B'] -> IndexSlices[:, ['A', 'B']] kinds = (ABCSeries, np.ndarray, Index, list, str) if isinstance(slice_, kinds): slice_ = IndexSlice[:, slice_] def pred(part): # true when slice does *not* reduce, False when part is a tuple, ...
<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_numeric_slice(df, slice_, include_bool=False): """ want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is...
if slice_ is None: dtypes = [np.number] if include_bool: dtypes.append(bool) slice_ = IndexSlice[:, df.select_dtypes(include=dtypes).columns] return slice_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _has_valid_tuple(self, key): """ check the key for valid keys across my indexer """
for i, k in enumerate(key): if i >= self.obj.ndim: raise IndexingError('Too many indexers') try: self._validate_key(k, i) except ValueError: raise ValueError("Location based indexing can only have " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _has_valid_positional_setitem_indexer(self, indexer): """ validate that an positional indexer cannot enlarge its target will raise if needed, does not modify...
if isinstance(indexer, dict): raise IndexError("{0} cannot enlarge its target object" .format(self.name)) else: if not isinstance(indexer, tuple): indexer = self._tuplify(indexer) for ax, i in zip(self.obj.axes, 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 _multi_take_opportunity(self, tup): """ Check whether there is the possibility to use ``_multi_take``. Currently the limit is that all axes being indexed mus...
if not all(is_list_like_indexer(x) for x in tup): return False # just too complicated if any(com.is_bool_indexer(x) for x in tup): return False 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 _multi_take(self, tup): """ Create the indexers for the passed tuple of keys, and execute the take operation. This allows the take operation to be executed a...
# GH 836 o = self.obj d = {axis: self._get_listlike_indexer(key, axis) for (key, axis) in zip(tup, o._AXIS_ORDERS)} return o._reindex_with_indexers(d, copy=True, allow_dups=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 _get_listlike_indexer(self, key, axis, raise_missing=False): """ Transform a list-like of keys into a new index and an indexer. Parameters key : list-like Ta...
o = self.obj ax = o._get_axis(axis) # Have the index compute an indexer or return None # if it cannot handle: indexer, keyarr = ax._convert_listlike_indexer(key, kind=self.name) # We only act on all found 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 _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False): """ Convert indexing key into something we can use to do actual fancy indexi...
if axis is None: axis = self.axis or 0 labels = self.obj._get_axis(axis) if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) # try to find out correct indexer, if not type correct raise try: obj = self._convert_scalar_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 _get_slice_axis(self, slice_obj, axis=None): """ this is pretty simple as we just have to deal with labels """
if axis is None: axis = self.axis or 0 obj = self.obj if not need_slice(slice_obj): return obj.copy(deep=False) labels = obj._get_axis(axis) indexer = labels.slice_indexer(slice_obj.start, slice_obj.stop, slice_obj...
<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_integer(self, key, axis): """ Check that 'key' is a valid position in the desired axis. Parameters key : int Requested position axis : int Desired ...
len_axis = len(self.obj._get_axis(axis)) if key >= len_axis or key < -len_axis: raise IndexError("single positional indexer is out-of-bounds")
<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_list_axis(self, key, axis=None): """ Return Series values by list or array of integers Parameters key : list-like positional indexer axis : int (can onl...
if axis is None: axis = self.axis or 0 try: return self.obj._take(key, axis=axis) except IndexError: # re-raise with different error message raise IndexError("positional indexers are out-of-bounds")
<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_to_indexer(self, obj, axis=None, is_setter=False): """ much simpler as we only have to deal with our valid types """
if axis is None: axis = self.axis or 0 # make need to convert a float key if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) elif is_float(obj): return self._convert_scalar_indexer(obj, axis) try: self._val...
<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_manager(sdf, columns, index): """ create and return the block manager from a dataframe of series, columns, index """
# from BlockManager perspective axes = [ensure_index(columns), ensure_index(index)] return create_block_manager_from_arrays( [sdf[c] for c in columns], columns, 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 stack_sparse_frame(frame): """ Only makes sense when fill_value is NaN """
lengths = [s.sp_index.npoints for _, s in frame.items()] nobs = sum(lengths) # this is pretty fast minor_codes = np.repeat(np.arange(len(frame.columns)), lengths) inds_to_concat = [] vals_to_concat = [] # TODO: Figure out whether this can be reached. # I think this currently can't be ...
<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_matrix(self, data, index, columns, dtype=None): """ Init self from ndarray or list of lists. """
data = prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) data = {idx: data[:, i] for i, idx in enumerate(columns)} return self._init_dict(data, index, columns, 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 _init_spmatrix(self, data, index, columns, dtype=None, fill_value=None): """ Init self from scipy.sparse matrix. """
index, columns = self._prep_index(data, index, columns) data = data.tocoo() N = len(index) # Construct a dict of SparseSeries sdict = {} values = Series(data.data, index=data.row, copy=False) for col, rowvals in values.groupby(data.col): # get_blocks...
<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_coo(self): """ Return the contents of the frame as a sparse SciPy COO matrix. .. versionadded:: 0.20.0 Returns ------- coo_matrix : scipy.sparse.spmatrix ...
try: from scipy.sparse import coo_matrix except ImportError: raise ImportError('Scipy is not installed') dtype = find_common_type(self.dtypes) if isinstance(dtype, SparseDtype): dtype = dtype.subtype cols, rows, datas = [], [], [] fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unpickle_sparse_frame_compat(self, state): """ Original pickle format """
series, cols, idx, fv, kind = state if not isinstance(cols, Index): # pragma: no cover from pandas.io.pickle import _unpickle_array columns = _unpickle_array(cols) else: columns = cols if not isinstance(idx, Index): # pragma: no cover ...
<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_dense(self): """ Convert to dense DataFrame Returns ------- df : DataFrame """
data = {k: v.to_dense() for k, v in self.items()} return DataFrame(data, index=self.index, columns=self.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 _apply_columns(self, func): """ Get new SparseDataFrame applying func to each columns """
new_data = {col: func(series) for col, series in self.items()} return self._constructor( data=new_data, index=self.index, columns=self.columns, default_fill_value=self.default_fill_value).__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 copy(self, deep=True): """ Make a copy of this SparseDataFrame """
result = super().copy(deep=deep) result._default_fill_value = self._default_fill_value result._default_kind = self._default_kind 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 _sanitize_column(self, key, value, **kwargs): """ Creates a new SparseArray from the input value. Parameters key : object value : scalar, Series, or array-li...
def sp_maker(x, index=None): return SparseArray(x, index=index, fill_value=self._default_fill_value, kind=self._default_kind) if isinstance(value, SparseSeries): clean = value.reindex(self.index).as_sparse_array( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cumsum(self, axis=0, *args, **kwargs): """ Return SparseDataFrame of cumulative sums over requested axis. Parameters axis : {0, 1} 0 for row-wise, 1 for colu...
nv.validate_cumsum(args, kwargs) if axis is None: axis = self._stat_axis_number return self.apply(lambda x: x.cumsum(), 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 apply(self, func, axis=0, broadcast=None, reduce=None, result_type=None): """ Analogous to DataFrame.apply, for SparseDataFrame Parameters func : function Fu...
if not len(self.columns): return self axis = self._get_axis_number(axis) if isinstance(func, np.ufunc): new_series = {} for k, v in self.items(): applied = func(v) applied.fill_value = func(v.fill_value) new_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 conda_package_to_pip(package): """ Convert a conda package to its pip equivalent. In most cases they are the same, those are the exceptions: - Packages that ...
if package in EXCLUDE: return package = re.sub('(?<=[^<>])=', '==', package).strip() for compare in ('<=', '>=', '=='): if compare not in package: continue pkg, version = package.split(compare) if pkg in RENAME: return ''.join((RENAME[pkg], compare...
<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_platform(values): """ try to do platform conversion, allow ndarray or list here """
if isinstance(values, (list, tuple)): values = construct_1d_object_array_from_listlike(list(values)) if getattr(values, 'dtype', None) == np.object_: if hasattr(values, '_values'): values = values._values values = lib.maybe_convert_objects(values) return 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 maybe_upcast_putmask(result, mask, other): """ A safe version of putmask that potentially upcasts the result. The result is replaced with the first N element...
if not isinstance(result, np.ndarray): raise ValueError("The result input must be a ndarray.") if mask.any(): # Two conversions for date-like dtypes that can't be done automatically # in np.place: # NaN -> NaT # integer or integer array -> date-like array 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 infer_dtype_from(val, pandas_dtype=False): """ interpret the dtype from a scalar or array. This is a convenience routines to infer dtype from a scalar or an ...
if is_scalar(val): return infer_dtype_from_scalar(val, pandas_dtype=pandas_dtype) return infer_dtype_from_array(val, pandas_dtype=pandas_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 infer_dtype_from_scalar(val, pandas_dtype=False): """ interpret the dtype from a scalar Parameters pandas_dtype : bool, default False whether to infer dtype ...
dtype = np.object_ # a 1-element ndarray if isinstance(val, np.ndarray): msg = "invalid ndarray passed to infer_dtype_from_scalar" if val.ndim != 0: raise ValueError(msg) dtype = val.dtype val = val.item() elif isinstance(val, str): # If we creat...
<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_dtype_from_array(arr, pandas_dtype=False): """ infer the dtype from a scalar or array Parameters arr : scalar or array pandas_dtype : bool, default Fal...
if isinstance(arr, np.ndarray): return arr.dtype, arr if not is_list_like(arr): arr = [arr] if pandas_dtype and is_extension_type(arr): return arr.dtype, arr elif isinstance(arr, ABCSeries): return arr.dtype, np.asarray(arr) # don't force numpy coerce with nan's...
<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_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing ...
tipo = None if hasattr(element, 'dtype'): tipo = element.dtype elif is_list_like(element): element = np.asarray(element) tipo = element.dtype return tipo
<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_upcast(values, fill_value=np.nan, dtype=None, copy=False): """ provide explicit type promotion and coercion Parameters values : the ndarray that we wan...
if is_extension_type(values): if copy: values = values.copy() else: if dtype is None: dtype = values.dtype new_dtype, fill_value = maybe_promote(dtype, fill_value) if new_dtype != values.dtype: values = values.astype(new_dtype) elif c...
<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_indexer_dtype(indexer, categories): """ coerce the indexer input array to the smallest dtype possible """
length = len(categories) if length < _int8_max: return ensure_int8(indexer) elif length < _int16_max: return ensure_int16(indexer) elif length < _int32_max: return ensure_int32(indexer) return ensure_int64(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 coerce_to_dtypes(result, dtypes): """ given a dtypes and a result set, coerce the result elements to the dtypes """
if len(result) != len(dtypes): raise AssertionError("_coerce_to_dtypes requires equal len arrays") def conv(r, dtype): try: if isna(r): pass elif dtype == _NS_DTYPE: r = tslibs.Timestamp(r) elif dtype == _TD_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 find_common_type(types): """ Find a common data type among the given dtypes. Parameters types : list of dtypes Returns ------- pandas extension or numpy dtyp...
if len(types) == 0: raise ValueError('no types given') first = types[0] # workaround for find_common_type([np.dtype('datetime64[ns]')] * 2) # => object if all(is_dtype_equal(first, t) for t in types[1:]): return first if any(isinstance(t, (PandasExtensionDtype, ExtensionDtyp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cast_scalar_to_array(shape, value, dtype=None): """ create np.ndarray of specified shape and dtype, filled with values Parameters shape : tuple value : scala...
if dtype is None: dtype, fill_value = infer_dtype_from_scalar(value) else: fill_value = value values = np.empty(shape, dtype=dtype) values.fill(fill_value) return 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 construct_1d_object_array_from_listlike(values): """ Transform any list-like object in a 1-dimensional numpy array of object dtype. Parameters values : any i...
# numpy will try to interpret nested lists as further dimensions, hence # making a 1D array that contains list-likes is a bit tricky: result = np.empty(len(values), dtype='object') result[:] = values 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 construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): """ Construct a new ndarray, coercing `values` to `dtype`, preserving NA. Parameters valu...
subarr = np.array(values, dtype=dtype, copy=copy) if dtype is not None and dtype.kind in ("U", "S"): # GH-21083 # We can't just return np.array(subarr, dtype='str') since # NumPy will convert the non-string objects into strings # Including NA values. Se we have to go # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): """ Make a scatter plot from two DataFrame columns Parameters data : DataFram...
import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y].values ax.scatter(xvals, yvals, **kwargs) ax.grid(grid) if by is not None: fig = _grouped_plot(plot_group, data, by=by, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, l...
_raise_if_no_mpl() _converter._WARN = False if by is not None: axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, figsize=figsize, sharex=sharex, sharey=sharey, layout=layout, bins=bins, xlabelsize=xlabelsize, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hist_series(self, by=None, ax=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, figsize=None, bins=10, **kwds): """ Draw histogram of ...
import matplotlib.pyplot as plt if by is None: if kwds.get('layout', None) is not None: raise ValueError("The 'layout' keyword is not supported when " "'by' is None") # hack until the plotting interface is a bit more unified fig = kwds.pop('figu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, rot=0, grid=True, ax=None, figsize=None, layout=None, sharex=False, sharey=True, **k...
_raise_if_no_mpl() _converter._WARN = False if subplots is True: naxes = len(grouped) fig, axes = _subplots(naxes=naxes, squeeze=False, ax=ax, sharex=sharex, sharey=sharey, figsize=figsize, layout=layout) axes = _flatten(ax...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _has_plotted_object(self, ax): """check whether ax has data"""
return (len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 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 result(self): """ Return result axes """
if self.subplots: if self.layout is not None and not is_list_like(self.ax): return self.axes.reshape(*self.layout) else: return self.axes else: sec_true = isinstance(self.secondary_y, bool) and self.secondary_y all_sec = (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 _post_plot_logic_common(self, ax, data): """Common post process for each axes"""
def get_label(i): try: return pprint_thing(data.index[i]) except Exception: return '' if self.orientation == 'vertical' or self.orientation is None: if self._need_to_set_index: xticklabels = [get_label(x) for x in ax....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _adorn_subplots(self): """Common post process unrelated to data"""
if len(self.axes) > 0: all_axes = self._get_subplots() nrows, ncols = self._get_axes_layout() _handle_shared_axes(axarr=all_axes, nplots=len(all_axes), naxes=nrows * ncols, nrows=nrows, ncols=ncols, sharex=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_style_colors(self, colors, kwds, col_num, label): """ Manage style and color based on column number and its label. Returns tuple of appropriate style ...
style = None if self.style is not None: if isinstance(self.style, list): try: style = self.style[col_num] except IndexError: pass elif isinstance(self.style, dict): style = self.style.get(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 line(self, x=None, y=None, **kwds): """ Plot DataFrame columns as lines. This function is useful to plot lines using DataFrame's values as coordinates. Param...
return self(kind='line', x=x, y=y, **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 bar(self, x=None, y=None, **kwds): """ Vertical bar plot. A bar plot is a plot that presents categorical data with rectangular bars with lengths proportional...
return self(kind='bar', x=x, y=y, **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 barh(self, x=None, y=None, **kwds): """ Make a horizontal bar plot. A horizontal bar plot is a plot that presents quantitative data with rectangular bars wit...
return self(kind='barh', x=x, y=y, **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 hist(self, by=None, bins=10, **kwds): """ Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This fu...
return self(kind='hist', by=by, bins=bins, **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 area(self, x=None, y=None, **kwds): """ Draw a stacked area plot. An area plot displays quantitative data visually. This function wraps the matplotlib area f...
return self(kind='area', x=x, y=y, **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 scatter(self, x, y, s=None, c=None, **kwds): """ Create a scatter plot with varying marker point size and color. The coordinates of each point are defined by...
return self(kind='scatter', x=x, y=y, c=c, s=s, **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 hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwds): """ Generate a hexagonal binning plot. Generate a hexagonal binning plot of `x` ve...
if reduce_C_function is not None: kwds['reduce_C_function'] = reduce_C_function if gridsize is not None: kwds['gridsize'] = gridsize return self(kind='hexbin', x=x, y=y, C=C, **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 _get_combined_index(indexes, intersect=False, sort=False): """ Return the union or intersection of indexes. Parameters indexes : list of Index or list object...
# TODO: handle index names! indexes = _get_distinct_objs(indexes) if len(indexes) == 0: index = Index([]) elif len(indexes) == 1: index = indexes[0] elif intersect: index = indexes[0] for other in indexes[1:]: index = index.intersection(other) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _union_indexes(indexes, sort=True): """ Return the union of indexes. The behavior of sort and names is not consistent. Parameters indexes : list of Index or ...
if len(indexes) == 0: raise AssertionError('Must have at least 1 Index to union') if len(indexes) == 1: result = indexes[0] if isinstance(result, list): result = Index(sorted(result)) return result indexes, kind = _sanitize_and_check(indexes) def _unique_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 _sanitize_and_check(indexes): """ Verify the type of indexes and convert lists to Index. Cases: Lists are sorted and converted to Index. TYPE = 'special' if ...
kinds = list({type(index) for index in indexes}) if list in kinds: if len(kinds) > 1: indexes = [Index(com.try_sort(x)) if not isinstance(x, Index) else x for x in indexes] kinds.remove(list) else: return indexes...
<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_consensus_names(indexes): """ Give a consensus 'names' to indexes. If there's exactly one non-empty 'names', return this, otherwise, return empty. Param...
# find the non-none names, need to tupleify to make # the set hashable, then reverse on return consensus_names = {tuple(i.names) for i in indexes if com._any_not_none(*i.names)} if len(consensus_names) == 1: return list(list(consensus_names)[0]) return [None] * 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 _all_indexes_same(indexes): """ Determine if all indexes contain the same elements. Parameters indexes : list of Index objects Returns ------- bool True if a...
first = indexes[0] for index in indexes[1:]: if not first.equals(index): return False 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 _convert_params(sql, params): """Convert SQL and params args to DBAPI2.0 compliant format."""
args = [sql] if params is not None: if hasattr(params, 'keys'): # test if params is a mapping args += [params] else: args += [list(params)] return args
<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_parse_dates_argument(parse_dates): """Process parse_dates argument for read_sql functions"""
# handle non-list entries for parse_dates gracefully if parse_dates is True or parse_dates is None or parse_dates is False: parse_dates = [] elif not hasattr(parse_dates, '__iter__'): parse_dates = [parse_dates] return parse_dates
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_date_columns(data_frame, parse_dates): """ Force non-datetime columns to be read as such. Supports both string formatted and integer timestamp columns...
parse_dates = _process_parse_dates_argument(parse_dates) # we want to coerce datetime64_tz dtypes for now to UTC # we could in theory do a 'nice' conversion from a FixedOffset tz # GH11216 for col_name, df_col in data_frame.iteritems(): if is_datetime64tz_dtype(df_col) or col_name in parse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_result(data, columns, index_col=None, coerce_float=True, parse_dates=None): """Wrap result set of query in a DataFrame."""
frame = DataFrame.from_records(data, columns=columns, coerce_float=coerce_float) frame = _parse_date_columns(frame, parse_dates) if index_col is not None: frame.set_index(index_col, inplace=True) return frame
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(sql, con, cur=None, params=None): """ Execute the given SQL query using the provided connection object. Parameters sql : string SQL query to be execu...
if cur is None: pandas_sql = pandasSQL_builder(con) else: pandas_sql = pandasSQL_builder(cur, is_cursor=True) args = _convert_params(sql, params) return pandas_sql.execute(*args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_table(table_name, con, schema=None): """ Check if DataBase has named table. Parameters table_name: string Name of SQL table. con: SQLAlchemy connectable(...
pandas_sql = pandasSQL_builder(con, schema=schema) return pandas_sql.has_table(table_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 pandasSQL_builder(con, schema=None, meta=None, is_cursor=False): """ Convenience function to return the correct PandasSQL subclass based on the provided para...
# When support for DBAPI connections is removed, # is_cursor should not be necessary. con = _engine_builder(con) if _is_sqlalchemy_connectable(con): return SQLDatabase(con, schema=schema, meta=meta) elif isinstance(con, str): raise ImportError("Using URI string without sqlalchemy 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 get_schema(frame, name, keys=None, con=None, dtype=None): """ Get the SQL db table schema for the given frame. Parameters frame : DataFrame name : string nam...
pandas_sql = pandasSQL_builder(con=con) return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=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 _execute_insert(self, conn, keys, data_iter): """Execute SQL statement inserting data Parameters conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connect...
data = [dict(zip(keys, row)) for row in data_iter] conn.execute(self.table.insert(), 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 _query_iterator(self, result, chunksize, columns, coerce_float=True, parse_dates=None): """Return generator through chunked result set."""
while True: data = result.fetchmany(chunksize) if not data: break else: self.frame = DataFrame.from_records( data, columns=columns, coerce_float=coerce_float) self._harmonize_columns(parse_dates=parse_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 _harmonize_columns(self, parse_dates=None): """ Make the DataFrame's column types align with the SQL table column types. Need to work around limited NA value...
parse_dates = _process_parse_dates_argument(parse_dates) for sql_col in self.table.columns: col_name = sql_col.name try: df_col = self.frame[col_name] # Handle date parsing upfront; don't try to convert columns # twice ...
<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_table_setup(self): """ Return a list of SQL statements that creates a table reflecting the structure of a DataFrame. The first entry will be a CREATE...
column_names_and_types = self._get_column_names_and_types( self._sql_type_name ) pat = re.compile(r'\s+') column_names = [col_name for col_name, _, _ in column_names_and_types] if any(map(pat.search, column_names)): warnings.warn(_SAFE_NAMES_WARNING, sta...
<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_to_categorical(array): """ Coerce to a categorical if a series is given. Internal use ONLY. """
if isinstance(array, (ABCSeries, ABCCategoricalIndex)): return array._values elif isinstance(array, np.ndarray): return Categorical(array) return array
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(cat, key, container): """ Helper for membership check for ``key`` in ``cat``. This is a helper method for :method:`__contains__` and :class:`Categor...
hash(key) # get location of key in categories. # If a KeyError, the key isn't in categories, so logically # can't be in container either. try: loc = cat.categories.get_loc(key) except KeyError: return False # loc is the location of key in categories, but also the *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 _get_codes_for_values(values, categories): """ utility routine to turn values into codes given the specified categories """
from pandas.core.algorithms import _get_data_algo, _hashtables dtype_equal = is_dtype_equal(values.dtype, categories.dtype) if dtype_equal: # To prevent erroneous dtype coercion in _get_data_algo, retrieve # the underlying numpy array. gh-22702 values = getattr(values, '_ndarray_va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _recode_for_categories(codes, old_categories, new_categories): """ Convert a set of codes for to a new set of categories Parameters codes : array old_categor...
from pandas.core.algorithms import take_1d if len(old_categories) == 0: # All null anyway, so just retain the nulls return codes.copy() elif new_categories.equals(old_categories): # Same categories, so no need to actually recode return codes.copy() indexer = coerce_inde...
<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_from_iterable(values): """ Factorize an input `values` into `categories` and `codes`. Preserves categorical dtype in `categories`. *This is an int...
from pandas.core.indexes.category import CategoricalIndex if not is_list_like(values): raise TypeError("Input must be list-like") if is_categorical(values): if isinstance(values, (ABCCategoricalIndex, ABCSeries)): values = values._values categories = CategoricalIndex(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 _factorize_from_iterables(iterables): """ A higher-level wrapper over `_factorize_from_iterable`. *This is an internal function* Parameters iterables : list-...
if len(iterables) == 0: # For consistency, it should return a list of 2 lists. return [[], []] return map(list, lzip(*[_factorize_from_iterable(it) for it in iterables]))
<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): """ Coerce this type to another dtype Parameters dtype : numpy dtype or pandas type copy : bool, default True By default, ast...
if is_categorical_dtype(dtype): # GH 10696/18593 dtype = self.dtype.update_dtype(dtype) self = self.copy() if copy else self if dtype == self.dtype: return self return self._set_dtype(dtype) return np.array(self, dtype=dtype, c...
<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_inferred_categories(cls, inferred_categories, inferred_codes, dtype, true_values=None): """ Construct a Categorical from inferred values. For inferred ...
from pandas import Index, to_numeric, to_datetime, to_timedelta cats = Index(inferred_categories) known_categories = (isinstance(dtype, CategoricalDtype) and dtype.categories is not None) if known_categories: # Convert to a specialized type 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 from_codes(cls, codes, categories=None, ordered=None, dtype=None): """ Make a Categorical type from codes and categories or dtype. This constructor is useful...
dtype = CategoricalDtype._from_values_or_dtype(categories=categories, ordered=ordered, dtype=dtype) if dtype.categories is None: msg = ("The categories must be provided in 'categori...
<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_codes(self): """ Get the codes. Returns ------- codes : integer array view A non writable view of the `codes` array. """
v = self._codes.view() v.flags.writeable = False 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 _set_categories(self, categories, fastpath=False): """ Sets new categories inplace Parameters fastpath : bool, default False Don't perform validation of the ...
if fastpath: new_dtype = CategoricalDtype._from_fastpath(categories, self.ordered) else: new_dtype = CategoricalDtype(categories, ordered=self.ordered) if (not fastpath and self.dtype.categories is not None and ...
<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_dtype(self, dtype): """ Internal method for directly updating the CategoricalDtype Parameters dtype : CategoricalDtype Notes ----- We don't do any valid...
codes = _recode_for_categories(self.codes, self.categories, dtype.categories) return type(self)(codes, dtype=dtype, fastpath=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 set_ordered(self, value, inplace=False): """ Set the ordered attribute to the boolean value. Parameters value : bool Set whether this categorical is ordered ...
inplace = validate_bool_kwarg(inplace, 'inplace') new_dtype = CategoricalDtype(self.categories, ordered=value) cat = self if inplace else self.copy() cat._dtype = new_dtype if not inplace: return cat