Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def is_sparse(arr):
from pandas.core.arrays.sparse import SparseDtype
dtype = getattr(arr, 'dtype', arr)
return isinstance(dtype, SparseDtype) | [
"\n Check whether an array-like is a 1-D pandas sparse array.\n\n Check that the one-dimensional array-like is a pandas sparse array.\n Returns True if it is a pandas sparse array, not another type of\n sparse array.\n\n Parameters\n ----------\n arr : array-like\n Array-like to check.\n... |
Please provide a description of the function:def is_scipy_sparse(arr):
global _is_scipy_sparse
if _is_scipy_sparse is None:
try:
from scipy.sparse import issparse as _is_scipy_sparse
except ImportError:
_is_scipy_sparse = lambda _: False
return _is_scipy_spars... | [
"\n Check whether an array-like is a scipy.sparse.spmatrix instance.\n\n Parameters\n ----------\n arr : array-like\n The array-like to check.\n\n Returns\n -------\n boolean\n Whether or not the array-like is a scipy.sparse.spmatrix instance.\n\n Notes\n -----\n If scipy... |
Please provide a description of the function:def is_offsetlike(arr_or_obj):
if isinstance(arr_or_obj, ABCDateOffset):
return True
elif (is_list_like(arr_or_obj) and len(arr_or_obj) and
is_object_dtype(arr_or_obj)):
return all(isinstance(x, ABCDateOffset) for x in arr_or_obj)
r... | [
"\n Check if obj or all elements of list-like is DateOffset\n\n Parameters\n ----------\n arr_or_obj : object\n\n Returns\n -------\n boolean\n Whether the object is a DateOffset or listlike of DatetOffsets\n\n Examples\n --------\n >>> is_offsetlike(pd.DateOffset(days=1))\n ... |
Please provide a description of the function:def is_period(arr):
warnings.warn("'is_period' is deprecated and will be removed in a future "
"version. Use 'is_period_dtype' or is_period_arraylike' "
"instead.", FutureWarning, stacklevel=2)
return isinstance(arr, ABCPer... | [
"\n Check whether an array-like is a periodical index.\n\n .. deprecated:: 0.24.0\n\n Parameters\n ----------\n arr : array-like\n The array-like to check.\n\n Returns\n -------\n boolean\n Whether or not the array-like is a periodical index.\n\n Examples\n --------\n ... |
Please provide a description of the function:def is_string_dtype(arr_or_dtype):
# TODO: gh-15585: consider making the checks stricter.
def condition(dtype):
return dtype.kind in ('O', 'S', 'U') and not is_period_dtype(dtype)
return _is_dtype(arr_or_dtype, condition) | [
"\n Check whether the provided array or dtype is of the string dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array or dtype to check.\n\n Returns\n -------\n boolean\n Whether or not the array or dtype is of the string dtype.\n\n Examples\n --------\n ... |
Please provide a description of the function:def is_period_arraylike(arr):
if isinstance(arr, (ABCPeriodIndex, ABCPeriodArray)):
return True
elif isinstance(arr, (np.ndarray, ABCSeries)):
return is_period_dtype(arr.dtype)
return getattr(arr, 'inferred_type', None) == 'period' | [
"\n Check whether an array-like is a periodical array-like or PeriodIndex.\n\n Parameters\n ----------\n arr : array-like\n The array-like to check.\n\n Returns\n -------\n boolean\n Whether or not the array-like is a periodical array-like or\n PeriodIndex instance.\n\n ... |
Please provide a description of the function:def is_datetime_arraylike(arr):
if isinstance(arr, ABCDatetimeIndex):
return True
elif isinstance(arr, (np.ndarray, ABCSeries)):
return (is_object_dtype(arr.dtype)
and lib.infer_dtype(arr, skipna=False) == 'datetime')
return ... | [
"\n Check whether an array-like is a datetime array-like or DatetimeIndex.\n\n Parameters\n ----------\n arr : array-like\n The array-like to check.\n\n Returns\n -------\n boolean\n Whether or not the array-like is a datetime array-like or\n DatetimeIndex.\n\n Examples\... |
Please provide a description of the function:def is_datetimelike(arr):
return (is_datetime64_dtype(arr) or is_datetime64tz_dtype(arr) or
is_timedelta64_dtype(arr) or
isinstance(arr, ABCPeriodIndex)) | [
"\n Check whether an array-like is a datetime-like array-like.\n\n Acceptable datetime-like objects are (but not limited to) datetime\n indices, periodic indices, and timedelta indices.\n\n Parameters\n ----------\n arr : array-like\n The array-like to check.\n\n Returns\n -------\n ... |
Please provide a description of the function:def is_dtype_equal(source, target):
try:
source = _get_dtype(source)
target = _get_dtype(target)
return source == target
except (TypeError, AttributeError):
# invalid comparison
# object == category will hit this
... | [
"\n Check if two dtypes are equal.\n\n Parameters\n ----------\n source : The first dtype to compare\n target : The second dtype to compare\n\n Returns\n ----------\n boolean\n Whether or not the two dtypes are equal.\n\n Examples\n --------\n >>> is_dtype_equal(int, float)\n... |
Please provide a description of the function:def is_dtype_union_equal(source, target):
source = _get_dtype(source)
target = _get_dtype(target)
if is_categorical_dtype(source) and is_categorical_dtype(target):
# ordered False for both
return source.ordered is target.ordered
return is... | [
"\n Check whether two arrays have compatible dtypes to do a union.\n numpy types are checked with ``is_dtype_equal``. Extension types are\n checked separately.\n\n Parameters\n ----------\n source : The first dtype to compare\n target : The second dtype to compare\n\n Returns\n ----------... |
Please provide a description of the function:def is_datetime64_ns_dtype(arr_or_dtype):
if arr_or_dtype is None:
return False
try:
tipo = _get_dtype(arr_or_dtype)
except TypeError:
if is_datetime64tz_dtype(arr_or_dtype):
tipo = _get_dtype(arr_or_dtype.dtype)
... | [
"\n Check whether the provided array or dtype is of the datetime64[ns] dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array or dtype to check.\n\n Returns\n -------\n boolean\n Whether or not the array or dtype is of the datetime64[ns] dtype.\n\n Examples\... |
Please provide a description of the function:def is_numeric_v_string_like(a, b):
is_a_array = isinstance(a, np.ndarray)
is_b_array = isinstance(b, np.ndarray)
is_a_numeric_array = is_a_array and is_numeric_dtype(a)
is_b_numeric_array = is_b_array and is_numeric_dtype(b)
is_a_string_array = is... | [
"\n Check if we are comparing a string-like object to a numeric ndarray.\n\n NumPy doesn't like to compare such objects, especially numeric arrays\n and scalar string-likes.\n\n Parameters\n ----------\n a : array-like, scalar\n The first object to check.\n b : array-like, scalar\n ... |
Please provide a description of the function:def is_datetimelike_v_numeric(a, b):
if not hasattr(a, 'dtype'):
a = np.asarray(a)
if not hasattr(b, 'dtype'):
b = np.asarray(b)
def is_numeric(x):
return is_integer_dtype(x) or is_float_dtype(x)
is_datetimelike = need... | [
"\n Check if we are comparing a datetime-like object to a numeric object.\n\n By \"numeric,\" we mean an object that is either of an int or float dtype.\n\n Parameters\n ----------\n a : array-like, scalar\n The first object to check.\n b : array-like, scalar\n The second object to c... |
Please provide a description of the function:def is_datetimelike_v_object(a, b):
if not hasattr(a, 'dtype'):
a = np.asarray(a)
if not hasattr(b, 'dtype'):
b = np.asarray(b)
is_datetimelike = needs_i8_conversion
return ((is_datetimelike(a) and is_object_dtype(b)) or
(is... | [
"\n Check if we are comparing a datetime-like object to an object instance.\n\n Parameters\n ----------\n a : array-like, scalar\n The first object to check.\n b : array-like, scalar\n The second object to check.\n\n Returns\n -------\n boolean\n Whether we return a comp... |
Please provide a description of the function:def needs_i8_conversion(arr_or_dtype):
if arr_or_dtype is None:
return False
return (is_datetime_or_timedelta_dtype(arr_or_dtype) or
is_datetime64tz_dtype(arr_or_dtype) or
is_period_dtype(arr_or_dtype)) | [
"\n Check whether the array or dtype should be converted to int64.\n\n An array-like or dtype \"needs\" such a conversion if the array-like\n or dtype is of a datetime-like dtype\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array or dtype to check.\n\n Returns\n -----... |
Please provide a description of the function:def is_bool_dtype(arr_or_dtype):
if arr_or_dtype is None:
return False
try:
dtype = _get_dtype(arr_or_dtype)
except TypeError:
return False
if isinstance(arr_or_dtype, CategoricalDtype):
arr_or_dtype = arr_or_dtype.catego... | [
"\n Check whether the provided array or dtype is of a boolean dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array or dtype to check.\n\n Returns\n -------\n boolean\n Whether or not the array or dtype is of a boolean dtype.\n\n Notes\n -----\n An Ex... |
Please provide a description of the function:def is_extension_type(arr):
if is_categorical(arr):
return True
elif is_sparse(arr):
return True
elif is_datetime64tz_dtype(arr):
return True
return False | [
"\n Check whether an array-like is of a pandas extension class instance.\n\n Extension classes include categoricals, pandas sparse objects (i.e.\n classes represented within the pandas library and not ones external\n to it like scipy sparse matrices), and datetime-like arrays.\n\n Parameters\n ---... |
Please provide a description of the function:def is_extension_array_dtype(arr_or_dtype):
dtype = getattr(arr_or_dtype, 'dtype', arr_or_dtype)
return (isinstance(dtype, ExtensionDtype) or
registry.find(dtype) is not None) | [
"\n Check if an object is a pandas extension array type.\n\n See the :ref:`Use Guide <extending.extension-types>` for more.\n\n Parameters\n ----------\n arr_or_dtype : object\n For array-like input, the ``.dtype`` attribute will\n be extracted.\n\n Returns\n -------\n bool\n ... |
Please provide a description of the function:def _is_dtype(arr_or_dtype, condition):
if arr_or_dtype is None:
return False
try:
dtype = _get_dtype(arr_or_dtype)
except (TypeError, ValueError, UnicodeEncodeError):
return False
return condition(dtype) | [
"\n Return a boolean if the condition is satisfied for the arr_or_dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like, str, np.dtype, or ExtensionArrayType\n The array-like or dtype object whose dtype we want to extract.\n condition : callable[Union[np.dtype, ExtensionDtype]]\n\n ... |
Please provide a description of the function:def _get_dtype(arr_or_dtype):
if arr_or_dtype is None:
raise TypeError("Cannot deduce dtype from null object")
# fastpath
elif isinstance(arr_or_dtype, np.dtype):
return arr_or_dtype
elif isinstance(arr_or_dtype, type):
return n... | [
"\n Get the dtype instance associated with an array\n or dtype object.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array-like or dtype object whose dtype we want to extract.\n\n Returns\n -------\n obj_dtype : The extract dtype instance from the\n pass... |
Please provide a description of the function:def _is_dtype_type(arr_or_dtype, condition):
if arr_or_dtype is None:
return condition(type(None))
# fastpath
if isinstance(arr_or_dtype, np.dtype):
return condition(arr_or_dtype.type)
elif isinstance(arr_or_dtype, type):
if iss... | [
"\n Return a boolean if the condition is satisfied for the arr_or_dtype.\n\n Parameters\n ----------\n arr_or_dtype : array-like\n The array-like or dtype object whose dtype we want to extract.\n condition : callable[Union[np.dtype, ExtensionDtypeType]]\n\n Returns\n -------\n bool : ... |
Please provide a description of the function:def infer_dtype_from_object(dtype):
if isinstance(dtype, type) and issubclass(dtype, np.generic):
# Type object from a dtype
return dtype
elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)):
# dtype object
tr... | [
"\n Get a numpy dtype.type-style object for a dtype object.\n\n This methods also includes handling of the datetime64[ns] and\n datetime64[ns, TZ] objects.\n\n If no dtype can be found, we return ``object``.\n\n Parameters\n ----------\n dtype : dtype, type\n The dtype object whose numpy... |
Please provide a description of the function:def _validate_date_like_dtype(dtype):
try:
typ = np.datetime_data(dtype)[0]
except ValueError as e:
raise TypeError('{error}'.format(error=e))
if typ != 'generic' and typ != 'ns':
msg = '{name!r} is too specific of a frequency, try p... | [
"\n Check whether the dtype is a date-like dtype. Raises an error if invalid.\n\n Parameters\n ----------\n dtype : dtype, type\n The dtype to check.\n\n Raises\n ------\n TypeError : The dtype could not be casted to a date-like dtype.\n ValueError : The dtype is an illegal date-like ... |
Please provide a description of the function:def pandas_dtype(dtype):
# short-circuit
if isinstance(dtype, np.ndarray):
return dtype.dtype
elif isinstance(dtype, (np.dtype, PandasExtensionDtype, ExtensionDtype)):
return dtype
# registered extension types
result = registry.find(... | [
"\n Convert input into a pandas only dtype object or a numpy dtype object.\n\n Parameters\n ----------\n dtype : object to be converted\n\n Returns\n -------\n np.dtype or a pandas dtype\n\n Raises\n ------\n TypeError if not a dtype\n "
] |
Please provide a description of the function:def _groupby_and_merge(by, on, left, right, _merge_pieces,
check_duplicates=True):
pieces = []
if not isinstance(by, (list, tuple)):
by = [by]
lby = left.groupby(by, sort=False)
# if we can groupby the rhs
# then we ... | [
"\n groupby & merge; we are always performing a left-by type operation\n\n Parameters\n ----------\n by: field to group\n on: duplicates field\n left: left frame\n right: right frame\n _merge_pieces: function for merging\n check_duplicates: boolean, default True\n should we check &... |
Please provide a description of the function:def merge_ordered(left, right, on=None,
left_on=None, right_on=None,
left_by=None, right_by=None,
fill_method=None, suffixes=('_x', '_y'),
how='outer'):
def _merger(x, y):
# perform the ... | [
"Perform merge with optional filling/interpolation designed for ordered\n data like time series data. Optionally perform group-wise merge (see\n examples)\n\n Parameters\n ----------\n left : DataFrame\n right : DataFrame\n on : label or list\n Field names to join on. Must be found in bo... |
Please provide a description of the function:def merge_asof(left, right, on=None,
left_on=None, right_on=None,
left_index=False, right_index=False,
by=None, left_by=None, right_by=None,
suffixes=('_x', '_y'),
tolerance=None,
allow... | [
"Perform an asof merge. This is similar to a left-join except that we\n match on nearest key rather than equal keys.\n\n Both DataFrames must be sorted by the key.\n\n For each row in the left DataFrame:\n\n - A \"backward\" search selects the last row in the right DataFrame whose\n 'on' key is... |
Please provide a description of the function:def _restore_dropped_levels_multijoin(left, right, dropped_level_names,
join_index, lindexer, rindexer):
def _convert_to_mulitindex(index):
if isinstance(index, MultiIndex):
return index
else:
... | [
"\n *this is an internal non-public method*\n\n Returns the levels, labels and names of a multi-index to multi-index join.\n Depending on the type of join, this method restores the appropriate\n dropped levels of the joined multi-index.\n The method relies on lidx, rindexer which hold the index posit... |
Please provide a description of the function:def _maybe_restore_index_levels(self, result):
names_to_restore = []
for name, left_key, right_key in zip(self.join_names,
self.left_on,
self.right_on):
... | [
"\n Restore index levels specified as `on` parameters\n\n Here we check for cases where `self.left_on` and `self.right_on` pairs\n each reference an index level in their respective DataFrames. The\n joined columns corresponding to these pairs are then restored to the\n index of `r... |
Please provide a description of the function:def _get_join_indexers(self):
return _get_join_indexers(self.left_join_keys,
self.right_join_keys,
sort=self.sort,
how=self.how) | [
" return the join indexers "
] |
Please provide a description of the function:def _create_join_index(self, index, other_index, indexer,
other_indexer, how='left'):
join_index = index.take(indexer)
if (self.how in (how, 'outer') and
not isinstance(other_index, MultiIndex)):
... | [
"\n Create a join index by rearranging one index to match another\n\n Parameters\n ----------\n index: Index being rearranged\n other_index: Index used to supply values not found in index\n indexer: how to rearrange index\n how: replacement is only necessary if index... |
Please provide a description of the function:def _get_merge_keys(self):
left_keys = []
right_keys = []
join_names = []
right_drop = []
left_drop = []
left, right = self.left, self.right
is_lkey = lambda x: is_array_like(x) and len(x) == len(left)
... | [
"\n Note: has side effects (copy/delete key columns)\n\n Parameters\n ----------\n left\n right\n on\n\n Returns\n -------\n left_keys, right_keys\n "
] |
Please provide a description of the function:def _get_join_indexers(self):
def flip(xs):
labels = list(string.ascii_lowercase[:len(xs)])
dtypes = [x.dtype for x in xs]
labeled_dtypes = list(zip(labels, dtypes))
return np.array(lzip(*xs), lab... | [
" return the join indexers ",
" unlike np.transpose, this returns an array of tuples "
] |
Please provide a description of the function:def is_dtype(cls, dtype):
dtype = getattr(dtype, 'dtype', dtype)
if isinstance(dtype, (ABCSeries, ABCIndexClass,
ABCDataFrame, np.dtype)):
# https://github.com/pandas-dev/pandas/issues/22960
# av... | [
"Check if we match 'dtype'.\n\n Parameters\n ----------\n dtype : object\n The object to check.\n\n Returns\n -------\n is_dtype : bool\n\n Notes\n -----\n The default implementation is True if\n\n 1. ``cls.construct_from_string(dtype)... |
Please provide a description of the function:def cat_core(list_of_columns, sep):
list_with_sep = [sep] * (2 * len(list_of_columns) - 1)
list_with_sep[::2] = list_of_columns
return np.sum(list_with_sep, axis=0) | [
"\n Auxiliary function for :meth:`str.cat`\n\n Parameters\n ----------\n list_of_columns : list of numpy arrays\n List of arrays to be concatenated with sep;\n these arrays may not contain NaNs!\n sep : string\n The separator string for concatenating the columns\n\n Returns\n ... |
Please provide a description of the function:def str_count(arr, pat, flags=0):
regex = re.compile(pat, flags=flags)
f = lambda x: len(regex.findall(x))
return _na_map(f, arr, dtype=int) | [
"\n Count occurrences of pattern in each string of the Series/Index.\n\n This function is used to count the number of times a particular regex\n pattern is repeated in each of the string elements of the\n :class:`~pandas.Series`.\n\n Parameters\n ----------\n pat : str\n Valid regular ex... |
Please provide a description of the function:def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):
if regex:
if not case:
flags |= re.IGNORECASE
regex = re.compile(pat, flags=flags)
if regex.groups > 0:
warnings.warn("This pattern has match gro... | [
"\n Test if pattern or regex is contained within a string of a Series or Index.\n\n Return boolean Series or Index based on whether a given pattern or regex is\n contained within a string of a Series or Index.\n\n Parameters\n ----------\n pat : str\n Character sequence or regular expressio... |
Please provide a description of the function:def str_startswith(arr, pat, na=np.nan):
f = lambda x: x.startswith(pat)
return _na_map(f, arr, na, dtype=bool) | [
"\n Test if the start of each string element matches a pattern.\n\n Equivalent to :meth:`str.startswith`.\n\n Parameters\n ----------\n pat : str\n Character sequence. Regular expressions are not accepted.\n na : object, default NaN\n Object shown if element tested is not a string.\n... |
Please provide a description of the function:def str_endswith(arr, pat, na=np.nan):
f = lambda x: x.endswith(pat)
return _na_map(f, arr, na, dtype=bool) | [
"\n Test if the end of each string element matches a pattern.\n\n Equivalent to :meth:`str.endswith`.\n\n Parameters\n ----------\n pat : str\n Character sequence. Regular expressions are not accepted.\n na : object, default NaN\n Object shown if element tested is not a string.\n\n ... |
Please provide a description of the function:def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True):
r
# Check whether repl is valid (GH 13438, GH 15055)
if not (is_string_like(repl) or callable(repl)):
raise TypeError("repl must be a string or callable")
is_compiled_re = is_re(... | [
"\n Replace occurrences of pattern/regex in the Series/Index with\n some other string. Equivalent to :meth:`str.replace` or\n :func:`re.sub`.\n\n Parameters\n ----------\n pat : str or compiled regex\n String can be a character sequence or regular expression.\n\n .. versionadded:: 0.... |
Please provide a description of the function:def str_repeat(arr, repeats):
if is_scalar(repeats):
def scalar_rep(x):
try:
return bytes.__mul__(x, repeats)
except TypeError:
return str.__mul__(x, repeats)
return _na_map(scalar_rep, arr)
... | [
"\n Duplicate each string in the Series or Index.\n\n Parameters\n ----------\n repeats : int or sequence of int\n Same value for all (int) or different value per (sequence).\n\n Returns\n -------\n Series or Index of object\n Series or Index of repeated string objects specified b... |
Please provide a description of the function:def str_match(arr, pat, case=True, flags=0, na=np.nan):
if not case:
flags |= re.IGNORECASE
regex = re.compile(pat, flags=flags)
dtype = bool
f = lambda x: bool(regex.match(x))
return _na_map(f, arr, na, dtype=dtype) | [
"\n Determine if each string matches a regular expression.\n\n Parameters\n ----------\n pat : str\n Character sequence or regular expression.\n case : bool, default True\n If True, case sensitive.\n flags : int, default 0 (no flags)\n re module flags, e.g. re.IGNORECASE.\n ... |
Please provide a description of the function:def _groups_or_na_fun(regex):
if regex.groups == 0:
raise ValueError("pattern contains no capture groups")
empty_row = [np.nan] * regex.groups
def f(x):
if not isinstance(x, str):
return empty_row
m = regex.search(x)
... | [
"Used in both extract_noexpand and extract_frame"
] |
Please provide a description of the function:def _str_extract_noexpand(arr, pat, flags=0):
from pandas import DataFrame, Index
regex = re.compile(pat, flags=flags)
groups_or_na = _groups_or_na_fun(regex)
if regex.groups == 1:
result = np.array([groups_or_na(val)[0] for val in arr], dtype=... | [
"\n Find groups in each string in the Series using passed regular\n expression. This function is called from\n str_extract(expand=False), and can return Series, DataFrame, or\n Index.\n\n "
] |
Please provide a description of the function:def _str_extract_frame(arr, pat, flags=0):
from pandas import DataFrame
regex = re.compile(pat, flags=flags)
groups_or_na = _groups_or_na_fun(regex)
names = dict(zip(regex.groupindex.values(), regex.groupindex.keys()))
columns = [names.get(1 + i, i)... | [
"\n For each subject string in the Series, extract groups from the\n first match of regular expression pat. This function is called from\n str_extract(expand=True), and always returns a DataFrame.\n\n "
] |
Please provide a description of the function:def str_extract(arr, pat, flags=0, expand=True):
r
if not isinstance(expand, bool):
raise ValueError("expand must be True or False")
if expand:
return _str_extract_frame(arr._orig, pat, flags=flags)
else:
result, name = _str_extract_no... | [
"\n Extract capture groups in the regex `pat` as columns in a DataFrame.\n\n For each subject string in the Series, extract groups from the\n first match of regular expression `pat`.\n\n Parameters\n ----------\n pat : str\n Regular expression pattern with capturing groups.\n flags : int... |
Please provide a description of the function:def str_extractall(arr, pat, flags=0):
r
regex = re.compile(pat, flags=flags)
# the regex must contain capture groups.
if regex.groups == 0:
raise ValueError("pattern contains no capture groups")
if isinstance(arr, ABCIndexClass):
arr = ... | [
"\n For each subject string in the Series, extract groups from all\n matches of regular expression pat. When each subject string in the\n Series has exactly one match, extractall(pat).xs(0, level='match')\n is the same as extract(pat).\n\n .. versionadded:: 0.18.0\n\n Parameters\n ----------\n ... |
Please provide a description of the function:def str_get_dummies(arr, sep='|'):
arr = arr.fillna('')
try:
arr = sep + arr + sep
except TypeError:
arr = sep + arr.astype(str) + sep
tags = set()
for ts in arr.str.split(sep):
tags.update(ts)
tags = sorted(tags - {""})
... | [
"\n Split each string in the Series by sep and return a DataFrame\n of dummy/indicator variables.\n\n Parameters\n ----------\n sep : str, default \"|\"\n String to split on.\n\n Returns\n -------\n DataFrame\n Dummy variables corresponding to values of the Series.\n\n See A... |
Please provide a description of the function:def str_findall(arr, pat, flags=0):
regex = re.compile(pat, flags=flags)
return _na_map(regex.findall, arr) | [
"\n Find all occurrences of pattern or regular expression in the Series/Index.\n\n Equivalent to applying :func:`re.findall` to all the elements in the\n Series/Index.\n\n Parameters\n ----------\n pat : str\n Pattern or regular expression.\n flags : int, default 0\n Flags from ``... |
Please provide a description of the function:def str_find(arr, sub, start=0, end=None, side='left'):
if not isinstance(sub, str):
msg = 'expected a string object, not {0}'
raise TypeError(msg.format(type(sub).__name__))
if side == 'left':
method = 'find'
elif side == 'right':
... | [
"\n Return indexes in each strings in the Series/Index where the\n substring is fully contained between [start:end]. Return -1 on failure.\n\n Parameters\n ----------\n sub : str\n Substring being searched.\n start : int\n Left edge index.\n end : int\n Right edge index.\n ... |
Please provide a description of the function:def str_pad(arr, width, side='left', fillchar=' '):
if not isinstance(fillchar, str):
msg = 'fillchar must be a character, not {0}'
raise TypeError(msg.format(type(fillchar).__name__))
if len(fillchar) != 1:
raise TypeError('fillchar mus... | [
"\n Pad strings in the Series/Index up to width.\n\n Parameters\n ----------\n width : int\n Minimum width of resulting string; additional characters will be filled\n with character defined in `fillchar`.\n side : {'left', 'right', 'both'}, default 'left'\n Side from which to fil... |
Please provide a description of the function:def str_slice(arr, start=None, stop=None, step=None):
obj = slice(start, stop, step)
f = lambda x: x[obj]
return _na_map(f, arr) | [
"\n Slice substrings from each element in the Series or Index.\n\n Parameters\n ----------\n start : int, optional\n Start position for slice operation.\n stop : int, optional\n Stop position for slice operation.\n step : int, optional\n Step size for slice operation.\n\n R... |
Please provide a description of the function:def str_slice_replace(arr, start=None, stop=None, repl=None):
if repl is None:
repl = ''
def f(x):
if x[start:stop] == '':
local_stop = start
else:
local_stop = stop
y = ''
if start is not None:
... | [
"\n Replace a positional slice of a string with another value.\n\n Parameters\n ----------\n start : int, optional\n Left index position to use for the slice. If not specified (None),\n the slice is unbounded on the left, i.e. slice from the start\n of the string.\n stop : int, o... |
Please provide a description of the function:def str_strip(arr, to_strip=None, side='both'):
if side == 'both':
f = lambda x: x.strip(to_strip)
elif side == 'left':
f = lambda x: x.lstrip(to_strip)
elif side == 'right':
f = lambda x: x.rstrip(to_strip)
else: # pragma: no co... | [
"\n Strip whitespace (including newlines) from each string in the\n Series/Index.\n\n Parameters\n ----------\n to_strip : str or unicode\n side : {'left', 'right', 'both'}, default 'both'\n\n Returns\n -------\n Series or Index\n "
] |
Please provide a description of the function:def str_wrap(arr, width, **kwargs):
r
kwargs['width'] = width
tw = textwrap.TextWrapper(**kwargs)
return _na_map(lambda s: '\n'.join(tw.wrap(s)), arr) | [
"\n Wrap long strings in the Series/Index to be formatted in\n paragraphs with length less than a given width.\n\n This method has the same keyword parameters and defaults as\n :class:`textwrap.TextWrapper`.\n\n Parameters\n ----------\n width : int\n Maximum line width.\n expand_tabs... |
Please provide a description of the function:def str_get(arr, i):
def f(x):
if isinstance(x, dict):
return x.get(i)
elif len(x) > i >= -len(x):
return x[i]
return np.nan
return _na_map(f, arr) | [
"\n Extract element from each component at specified position.\n\n Extract element from lists, tuples, or strings in each element in the\n Series/Index.\n\n Parameters\n ----------\n i : int\n Position of element to extract.\n\n Returns\n -------\n Series or Index\n\n Examples\n... |
Please provide a description of the function:def str_decode(arr, encoding, errors="strict"):
if encoding in _cpython_optimized_decoders:
# CPython optimized implementation
f = lambda x: x.decode(encoding, errors)
else:
decoder = codecs.getdecoder(encoding)
f = lambda x: deco... | [
"\n Decode character string in the Series/Index using indicated encoding.\n Equivalent to :meth:`str.decode` in python2 and :meth:`bytes.decode` in\n python3.\n\n Parameters\n ----------\n encoding : str\n errors : str, optional\n\n Returns\n -------\n Series or Index\n "
] |
Please provide a description of the function:def str_encode(arr, encoding, errors="strict"):
if encoding in _cpython_optimized_encoders:
# CPython optimized implementation
f = lambda x: x.encode(encoding, errors)
else:
encoder = codecs.getencoder(encoding)
f = lambda x: enco... | [
"\n Encode character string in the Series/Index using indicated encoding.\n Equivalent to :meth:`str.encode`.\n\n Parameters\n ----------\n encoding : str\n errors : str, optional\n\n Returns\n -------\n encoded : Series/Index of objects\n "
] |
Please provide a description of the function:def copy(source):
"Copy a docstring from another source function (if present)"
def do_copy(target):
if source.__doc__:
target.__doc__ = source.__doc__
return target
return do_copy | [] |
Please provide a description of the function:def _get_series_list(self, others, ignore_index=False):
# Once str.cat defaults to alignment, this function can be simplified;
# will not need `ignore_index` and the second boolean output anymore
from pandas import Index, Series, DataFrame
... | [
"\n Auxiliary function for :meth:`str.cat`. Turn potentially mixed input\n into a list of Series (elements without an index must match the length\n of the calling Series/Index).\n\n Parameters\n ----------\n others : Series, Index, DataFrame, np.ndarray, list-like or list-l... |
Please provide a description of the function:def cat(self, others=None, sep=None, na_rep=None, join=None):
from pandas import Index, Series, concat
if isinstance(others, str):
raise ValueError("Did you mean to supply a `sep` keyword?")
if sep is None:
sep = ''
... | [
"\n Concatenate strings in the Series/Index with given separator.\n\n If `others` is specified, this function concatenates the Series/Index\n and elements of `others` element-wise.\n If `others` is not passed, then all values in the Series/Index are\n concatenated into a single st... |
Please provide a description of the function:def zfill(self, width):
result = str_pad(self._parent, width, side='left', fillchar='0')
return self._wrap_result(result) | [
"\n Pad strings in the Series/Index by prepending '0' characters.\n\n Strings in the Series/Index are padded with '0' characters on the\n left of the string to reach a total string length `width`. Strings\n in the Series/Index with length greater or equal to `width` are\n unchang... |
Please provide a description of the function:def normalize(self, form):
import unicodedata
f = lambda x: unicodedata.normalize(form, x)
result = _na_map(f, self._parent)
return self._wrap_result(result) | [
"\n Return the Unicode normal form for the strings in the Series/Index.\n For more information on the forms, see the\n :func:`unicodedata.normalize`.\n\n Parameters\n ----------\n form : {'NFC', 'NFKC', 'NFD', 'NFKD'}\n Unicode form\n\n Returns\n --... |
Please provide a description of the function:def get_sys_info():
"Returns system information as a dict"
blob = []
# get full commit hash
commit = None
if os.path.isdir(".git") and os.path.isdir("pandas"):
try:
pipe = subprocess.Popen('git log --format="%H" -n 1'.split(" "),
... | [] |
Please provide a description of the function:def whitelist_method_generator(base, klass, whitelist):
method_wrapper_template = \
%(doc)s
\
property_wrapper_template = \
%(doc)s\
for name in whitelist:
# don't override anything that was explicitly defined
# in ... | [
"\n Yields all GroupBy member defs for DataFrame/Series names in whitelist.\n\n Parameters\n ----------\n base : class\n base class\n klass : class\n class where members are defined.\n Should be Series or DataFrame\n whitelist : list\n list of names of klass methods to ... |
Please provide a description of the function:def _dispatch(name, *args, **kwargs):
def outer(self, *args, **kwargs):
def f(x):
x = self._shallow_copy(x, groupby=self._groupby)
return getattr(x, name)(*args, **kwargs)
return self._groupby.apply(f)... | [
"\n Dispatch to apply.\n "
] |
Please provide a description of the function:def _gotitem(self, key, ndim, subset=None):
# create a new object to prevent aliasing
if subset is None:
subset = self.obj
# we need to make a shallow copy of ourselves
# with the same groupby
kwargs = {attr: geta... | [
"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n "
] |
Please provide a description of the function:def to_str(s):
if isinstance(s, bytes):
s = s.decode('utf-8')
elif not isinstance(s, str):
s = str(s)
return s | [
"\n Convert bytes and non-string into Python 3 str\n "
] |
Please provide a description of the function:def set_function_name(f, name, cls):
f.__name__ = name
f.__qualname__ = '{klass}.{name}'.format(
klass=cls.__name__,
name=name)
f.__module__ = cls.__module__
return f | [
"\n Bind the name/qualname attributes of the function\n "
] |
Please provide a description of the function:def raise_with_traceback(exc, traceback=Ellipsis):
if traceback == Ellipsis:
_, _, traceback = sys.exc_info()
raise exc.with_traceback(traceback) | [
"\n Raise exception with existing traceback.\n If traceback is not passed, uses sys.exc_info() to get traceback.\n "
] |
Please provide a description of the function:def _convert_to_style(cls, style_dict):
from openpyxl.style import Style
xls_style = Style()
for key, value in style_dict.items():
for nk, nv in value.items():
if key == "borders":
(xls_style.b... | [
"\n converts a style_dict to an openpyxl style object\n Parameters\n ----------\n style_dict : style dictionary to convert\n "
] |
Please provide a description of the function:def _convert_to_style_kwargs(cls, style_dict):
_style_key_map = {
'borders': 'border',
}
style_kwargs = {}
for k, v in style_dict.items():
if k in _style_key_map:
k = _style_key_map[k]
... | [
"\n Convert a style_dict to a set of kwargs suitable for initializing\n or updating-on-copy an openpyxl v2 style object\n Parameters\n ----------\n style_dict : dict\n A dict with zero or more of the following keys (or their synonyms).\n 'font'\n ... |
Please provide a description of the function:def _convert_to_color(cls, color_spec):
from openpyxl.styles import Color
if isinstance(color_spec, str):
return Color(color_spec)
else:
return Color(**color_spec) | [
"\n Convert ``color_spec`` to an openpyxl v2 Color object\n Parameters\n ----------\n color_spec : str, dict\n A 32-bit ARGB hex string, or a dict with zero or more of the\n following keys.\n 'rgb'\n 'indexed'\n 'auto'\n ... |
Please provide a description of the function:def _convert_to_font(cls, font_dict):
from openpyxl.styles import Font
_font_key_map = {
'sz': 'size',
'b': 'bold',
'i': 'italic',
'u': 'underline',
'strike': 'strikethrough',
... | [
"\n Convert ``font_dict`` to an openpyxl v2 Font object\n Parameters\n ----------\n font_dict : dict\n A dict with zero or more of the following keys (or their synonyms).\n 'name'\n 'size' ('sz')\n 'bold' ('b')\n 'ita... |
Please provide a description of the function:def _convert_to_fill(cls, fill_dict):
from openpyxl.styles import PatternFill, GradientFill
_pattern_fill_key_map = {
'patternType': 'fill_type',
'patterntype': 'fill_type',
'fgColor': 'start_color',
... | [
"\n Convert ``fill_dict`` to an openpyxl v2 Fill object\n Parameters\n ----------\n fill_dict : dict\n A dict with one or more of the following keys (or their synonyms),\n 'fill_type' ('patternType', 'patterntype')\n 'start_color' ('fgColor', 'fgc... |
Please provide a description of the function:def _convert_to_side(cls, side_spec):
from openpyxl.styles import Side
_side_key_map = {
'border_style': 'style',
}
if isinstance(side_spec, str):
return Side(style=side_spec)
side_kwargs = {}
... | [
"\n Convert ``side_spec`` to an openpyxl v2 Side object\n Parameters\n ----------\n side_spec : str, dict\n A string specifying the border style, or a dict with zero or more\n of the following keys (or their synonyms).\n 'style' ('border_style')\n ... |
Please provide a description of the function:def _convert_to_border(cls, border_dict):
from openpyxl.styles import Border
_border_key_map = {
'diagonalup': 'diagonalUp',
'diagonaldown': 'diagonalDown',
}
border_kwargs = {}
for k, v in border_di... | [
"\n Convert ``border_dict`` to an openpyxl v2 Border object\n Parameters\n ----------\n border_dict : dict\n A dict with zero or more of the following keys (or their synonyms).\n 'left'\n 'right'\n 'top'\n 'bottom'\n ... |
Please provide a description of the function:def frame_apply(obj, func, axis=0, broadcast=None,
raw=False, reduce=None, result_type=None,
ignore_failures=False,
args=None, kwds=None):
axis = obj._get_axis_number(axis)
if axis == 0:
klass = FrameRowAp... | [
" construct and return a row or column based frame apply object "
] |
Please provide a description of the function:def get_result(self):
# dispatch to agg
if is_list_like(self.f) or is_dict_like(self.f):
return self.obj.aggregate(self.f, axis=self.axis,
*self.args, **self.kwds)
# all empty
if len... | [
" compute the results "
] |
Please provide a description of the function:def apply_empty_result(self):
# we are not asked to reduce or infer reduction
# so just return a copy of the existing object
if self.result_type not in ['reduce', None]:
return self.obj.copy()
# we may need to infer
... | [
"\n we have an empty result; at least 1 axis is 0\n\n we will try to apply the function to an empty\n series in order to see if this is a reduction function\n "
] |
Please provide a description of the function:def apply_raw(self):
try:
result = reduction.reduce(self.values, self.f, axis=self.axis)
except Exception:
result = np.apply_along_axis(self.f, self.axis, self.values)
# TODO: mixed type case
if result.ndim =... | [
" apply to the values as a numpy array "
] |
Please provide a description of the function:def wrap_results_for_axis(self):
results = self.results
result = self.obj._constructor(data=results)
if not isinstance(results[0], ABCSeries):
try:
result.index = self.res_columns
except ValueError:
... | [
" return the results for the rows "
] |
Please provide a description of the function:def wrap_results_for_axis(self):
results = self.results
# we have requested to expand
if self.result_type == 'expand':
result = self.infer_to_same_shape()
# we have a non-series and don't want inference
elif not ... | [
" return the results for the columns "
] |
Please provide a description of the function:def infer_to_same_shape(self):
results = self.results
result = self.obj._constructor(data=results)
result = result.T
# set the index
result.index = self.res_index
# infer dtypes
result = result.infer_objects... | [
" infer the results to the same shape as the input object "
] |
Please provide a description of the function:def cartesian_product(X):
msg = "Input must be a list-like of list-likes"
if not is_list_like(X):
raise TypeError(msg)
for x in X:
if not is_list_like(x):
raise TypeError(msg)
if len(X) == 0:
return []
lenX = np.... | [
"\n Numpy version of itertools.product.\n Sometimes faster (for large inputs)...\n\n Parameters\n ----------\n X : list-like of list-likes\n\n Returns\n -------\n product : list of ndarrays\n\n Examples\n --------\n >>> cartesian_product([list('ABC'), [1, 2]])\n [array(['A', 'A',... |
Please provide a description of the function:def _strip_schema(url):
result = parse_url(url, allow_fragments=False)
return result.netloc + result.path | [
"Returns the url without the s3:// part"
] |
Please provide a description of the function:def xception(c, k=8, n_middle=8):
"Preview version of Xception network. Not tested yet - use at own risk. No pretrained model yet."
layers = [
conv(3, k*4, 3, 2),
conv(k*4, k*8, 3),
ConvSkip(k*8, k*16, act=False),
ConvSkip(k*16, k*32),... | [] |
Please provide a description of the function:def get_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs):
m = get_language_model(self.nt, emb_sz, n_hid, n_layers, self.pad_idx, **kwargs)
model = SingleModel(to_gpu(m))
return RNN_Learner(self, model, opt_fn=opt_fn) | [
" Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module.\n\n Args:\n opt_fn (Optimizer): the torch optimizer function to use\n emb_sz (int): embedding size\n n_hid (int): number of hidden inputs\n n_layers (int): number of hidden lay... |
Please provide a description of the function:def from_text_files(cls, path, field, train, validation, test=None, bs=64, bptt=70, **kwargs):
trn_ds, val_ds, test_ds = ConcatTextDataset.splits(
path, text_field=field, train=train, validation=validation, test=test)
return cls(path, fie... | [
" Method used to instantiate a LanguageModelData object that can be used for a\n supported nlp task.\n\n Args:\n path (str): the absolute path in which temporary model data will be saved\n field (Field): torchtext field\n train (str): file location of the training ... |
Please provide a description of the function:def get_files(path:PathOrStr, extensions:Collection[str]=None, recurse:bool=False,
include:Optional[Collection[str]]=None)->FilePathList:
"Return list of files in `path` that have a suffix in `extensions`; optionally `recurse`."
if recurse:
res ... | [] |
Please provide a description of the function:def _databunch_load_empty(cls, path, fname:str='export.pkl'):
"Load an empty `DataBunch` from the exported file in `path/fname` with optional `tfms`."
sd = LabelLists.load_empty(path, fn=fname)
return sd.databunch() | [] |
Please provide a description of the function:def process(self, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: p.process(self)
... | [] |
Please provide a description of the function:def process_one(self, item:ItemBase, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `item`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: item ... | [] |
Please provide a description of the function:def reconstruct(self, t:Tensor, x:Tensor=None):
"Reconstruct one of the underlying item for its data `t`."
return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t) | [] |
Please provide a description of the function:def new(self, items:Iterator, processor:PreProcessors=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
... | [] |
Please provide a description of the function:def from_folder(cls, path:PathOrStr, extensions:Collection[str]=None, recurse:bool=True,
include:Optional[Collection[str]]=None, processor:PreProcessors=None, **kwargs)->'ItemList':
path = Path(path)
return cls(get_files(path, ext... | [
"Create an `ItemList` in `path` from the filenames that have a suffix in `extensions`.\n `recurse` determines if we search subfolders."
] |
Please provide a description of the function:def from_df(cls, df:DataFrame, path:PathOrStr='.', cols:IntsOrStrs=0, processor:PreProcessors=None, **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the inputs in the `cols` of `df`."
inputs = df.iloc[:,df_names_to_idx(cols, df)]
assert inp... | [] |
Please provide a description of the function:def from_csv(cls, path:PathOrStr, csv_name:str, cols:IntsOrStrs=0, delimiter:str=None, header:str='infer',
processor:PreProcessors=None, **kwargs)->'ItemList':
df = pd.read_csv(Path(path)/csv_name, delimiter=delimiter, header=header)
... | [
"Create an `ItemList` in `path` from the inputs in the `cols` of `path/csv_name`"
] |
Please provide a description of the function:def use_partial_data(self, sample_pct:float=0.01, seed:int=None)->'ItemList':
"Use only a sample of `sample_pct`of the full dataset and an optional `seed`."
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation(range_of(self))
... | [] |
Please provide a description of the function:def to_text(self, fn:str):
"Save `self.items` to `fn` in `self.path`."
with open(self.path/fn, 'w') as f: f.writelines([f'{o}\n' for o in self._relative_item_paths()]) | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.