INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Check whether an array-like is a periodical array-like or PeriodIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical array-like or PeriodIndex instance. Examples -------- ...
def is_period_arraylike(arr): """ Check whether an array-like is a periodical array-like or PeriodIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical array-like or PeriodInd...
Check whether an array-like is a datetime array-like or DatetimeIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a datetime array-like or DatetimeIndex. Examples -------- >>> is_...
def is_datetime_arraylike(arr): """ Check whether an array-like is a datetime array-like or DatetimeIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a datetime array-like or DatetimeI...
Check whether an array-like is a datetime-like array-like. Acceptable datetime-like objects are (but not limited to) datetime indices, periodic indices, and timedelta indices. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Wheth...
def is_datetimelike(arr): """ Check whether an array-like is a datetime-like array-like. Acceptable datetime-like objects are (but not limited to) datetime indices, periodic indices, and timedelta indices. Parameters ---------- arr : array-like The array-like to check. Returns...
Check if two dtypes are equal. Parameters ---------- source : The first dtype to compare target : The second dtype to compare Returns ---------- boolean Whether or not the two dtypes are equal. Examples -------- >>> is_dtype_equal(int, float) False >>> is_dtype...
def is_dtype_equal(source, target): """ Check if two dtypes are equal. Parameters ---------- source : The first dtype to compare target : The second dtype to compare Returns ---------- boolean Whether or not the two dtypes are equal. Examples -------- >>> is_dt...
Check whether two arrays have compatible dtypes to do a union. numpy types are checked with ``is_dtype_equal``. Extension types are checked separately. Parameters ---------- source : The first dtype to compare target : The second dtype to compare Returns ---------- boolean ...
def is_dtype_union_equal(source, target): """ Check whether two arrays have compatible dtypes to do a union. numpy types are checked with ``is_dtype_equal``. Extension types are checked separately. Parameters ---------- source : The first dtype to compare target : The second dtype to co...
Check whether the provided array or dtype is of the datetime64[ns] dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the datetime64[ns] dtype. Examples -------- >>> is...
def is_datetime64_ns_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of the datetime64[ns] dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of the datet...
Check if we are comparing a string-like object to a numeric ndarray. NumPy doesn't like to compare such objects, especially numeric arrays and scalar string-likes. Parameters ---------- a : array-like, scalar The first object to check. b : array-like, scalar The second object t...
def is_numeric_v_string_like(a, b): """ Check if we are comparing a string-like object to a numeric ndarray. NumPy doesn't like to compare such objects, especially numeric arrays and scalar string-likes. Parameters ---------- a : array-like, scalar The first object to check. b ...
Check if we are comparing a datetime-like object to a numeric object. By "numeric," we mean an object that is either of an int or float dtype. Parameters ---------- a : array-like, scalar The first object to check. b : array-like, scalar The second object to check. Returns ...
def is_datetimelike_v_numeric(a, b): """ Check if we are comparing a datetime-like object to a numeric object. By "numeric," we mean an object that is either of an int or float dtype. Parameters ---------- a : array-like, scalar The first object to check. b : array-like, scalar ...
Check if we are comparing a datetime-like object to an object instance. Parameters ---------- a : array-like, scalar The first object to check. b : array-like, scalar The second object to check. Returns ------- boolean Whether we return a comparing a datetime-like t...
def is_datetimelike_v_object(a, b): """ Check if we are comparing a datetime-like object to an object instance. Parameters ---------- a : array-like, scalar The first object to check. b : array-like, scalar The second object to check. Returns ------- boolean ...
Check whether the array or dtype should be converted to int64. An array-like or dtype "needs" such a conversion if the array-like or dtype is of a datetime-like dtype Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean W...
def needs_i8_conversion(arr_or_dtype): """ Check whether the array or dtype should be converted to int64. An array-like or dtype "needs" such a conversion if the array-like or dtype is of a datetime-like dtype Parameters ---------- arr_or_dtype : array-like The array or dtype to ch...
Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a boolean dtype. Notes ----- An ExtensionArray is considere...
def is_bool_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a boolean dtype. Notes...
Check whether an array-like is of a pandas extension class instance. Extension classes include categoricals, pandas sparse objects (i.e. classes represented within the pandas library and not ones external to it like scipy sparse matrices), and datetime-like arrays. Parameters ---------- arr : ...
def is_extension_type(arr): """ Check whether an array-like is of a pandas extension class instance. Extension classes include categoricals, pandas sparse objects (i.e. classes represented within the pandas library and not ones external to it like scipy sparse matrices), and datetime-like arrays. ...
Check if an object is a pandas extension array type. See the :ref:`Use Guide <extending.extension-types>` for more. Parameters ---------- arr_or_dtype : object For array-like input, the ``.dtype`` attribute will be extracted. Returns ------- bool Whether the `arr_o...
def is_extension_array_dtype(arr_or_dtype): """ Check if an object is a pandas extension array type. See the :ref:`Use Guide <extending.extension-types>` for more. Parameters ---------- arr_or_dtype : object For array-like input, the ``.dtype`` attribute will be extracted. ...
Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like, str, np.dtype, or ExtensionArrayType The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtype]] Returns ------...
def _is_dtype(arr_or_dtype, condition): """ Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like, str, np.dtype, or ExtensionArrayType The array-like or dtype object whose dtype we want to extract. condition : callable[Unio...
Get the dtype instance associated with an array or dtype object. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. Returns ------- obj_dtype : The extract dtype instance from the passed in array or dtype o...
def _get_dtype(arr_or_dtype): """ Get the dtype instance associated with an array or dtype object. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. Returns ------- obj_dtype : The extract dtype instance from the ...
Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtypeType]] Returns ------- bool : if the condition is s...
def _is_dtype_type(arr_or_dtype, condition): """ Return a boolean if the condition is satisfied for the arr_or_dtype. Parameters ---------- arr_or_dtype : array-like The array-like or dtype object whose dtype we want to extract. condition : callable[Union[np.dtype, ExtensionDtypeType]] ...
Get a numpy dtype.type-style object for a dtype object. This methods also includes handling of the datetime64[ns] and datetime64[ns, TZ] objects. If no dtype can be found, we return ``object``. Parameters ---------- dtype : dtype, type The dtype object whose numpy dtype.type-style ...
def infer_dtype_from_object(dtype): """ Get a numpy dtype.type-style object for a dtype object. This methods also includes handling of the datetime64[ns] and datetime64[ns, TZ] objects. If no dtype can be found, we return ``object``. Parameters ---------- dtype : dtype, type T...
Check whether the dtype is a date-like dtype. Raises an error if invalid. Parameters ---------- dtype : dtype, type The dtype to check. Raises ------ TypeError : The dtype could not be casted to a date-like dtype. ValueError : The dtype is an illegal date-like dtype (e.g. the ...
def _validate_date_like_dtype(dtype): """ Check whether the dtype is a date-like dtype. Raises an error if invalid. Parameters ---------- dtype : dtype, type The dtype to check. Raises ------ TypeError : The dtype could not be casted to a date-like dtype. ValueError : The d...
Convert input into a pandas only dtype object or a numpy dtype object. Parameters ---------- dtype : object to be converted Returns ------- np.dtype or a pandas dtype Raises ------ TypeError if not a dtype
def pandas_dtype(dtype): """ Convert input into a pandas only dtype object or a numpy dtype object. Parameters ---------- dtype : object to be converted Returns ------- np.dtype or a pandas dtype Raises ------ TypeError if not a dtype """ # short-circuit if isi...
groupby & merge; we are always performing a left-by type operation Parameters ---------- by: field to group on: duplicates field left: left frame right: right frame _merge_pieces: function for merging check_duplicates: boolean, default True should we check & clean duplicates
def _groupby_and_merge(by, on, left, right, _merge_pieces, check_duplicates=True): """ groupby & merge; we are always performing a left-by type operation Parameters ---------- by: field to group on: duplicates field left: left frame right: right frame _merge_p...
Perform merge with optional filling/interpolation designed for ordered data like time series data. Optionally perform group-wise merge (see examples) Parameters ---------- left : DataFrame right : DataFrame on : label or list Field names to join on. Must be found in both DataFrames....
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'): """Perform merge with optional filling/interpolation designed for ordered data like tim...
Perform an asof merge. This is similar to a left-join except that we match on nearest key rather than equal keys. Both DataFrames must be sorted by the key. For each row in the left DataFrame: - A "backward" search selects the last row in the right DataFrame whose 'on' key is less than or e...
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_exact_matches=True, direction...
*this is an internal non-public method* Returns the levels, labels and names of a multi-index to multi-index join. Depending on the type of join, this method restores the appropriate dropped levels of the joined multi-index. The method relies on lidx, rindexer which hold the index positions of left...
def _restore_dropped_levels_multijoin(left, right, dropped_level_names, join_index, lindexer, rindexer): """ *this is an internal non-public method* Returns the levels, labels and names of a multi-index to multi-index join. Depending on the type of join, this metho...
Restore index levels specified as `on` parameters Here we check for cases where `self.left_on` and `self.right_on` pairs each reference an index level in their respective DataFrames. The joined columns corresponding to these pairs are then restored to the index of `result`. **N...
def _maybe_restore_index_levels(self, result): """ Restore index levels specified as `on` parameters Here we check for cases where `self.left_on` and `self.right_on` pairs each reference an index level in their respective DataFrames. The joined columns corresponding to these pai...
return the join indexers
def _get_join_indexers(self): """ return the join indexers """ return _get_join_indexers(self.left_join_keys, self.right_join_keys, sort=self.sort, how=self.how)
Create a join index by rearranging one index to match another Parameters ---------- index: Index being rearranged other_index: Index used to supply values not found in index indexer: how to rearrange index how: replacement is only necessary if indexer based on other_inde...
def _create_join_index(self, index, other_index, indexer, other_indexer, how='left'): """ Create a join index by rearranging one index to match another Parameters ---------- index: Index being rearranged other_index: Index used to supply values...
Note: has side effects (copy/delete key columns) Parameters ---------- left right on Returns ------- left_keys, right_keys
def _get_merge_keys(self): """ Note: has side effects (copy/delete key columns) Parameters ---------- left right on Returns ------- left_keys, right_keys """ left_keys = [] right_keys = [] join_names = [] ...
return the join indexers
def _get_join_indexers(self): """ return the join indexers """ def flip(xs): """ unlike np.transpose, this returns an array of tuples """ labels = list(string.ascii_lowercase[:len(xs)]) dtypes = [x.dtype for x in xs] labeled_dtypes = list(zip(labels, dtyp...
Check if we match 'dtype'. Parameters ---------- dtype : object The object to check. Returns ------- is_dtype : bool Notes ----- The default implementation is True if 1. ``cls.construct_from_string(dtype)`` is an instance ...
def is_dtype(cls, dtype): """Check if we match 'dtype'. Parameters ---------- dtype : object The object to check. Returns ------- is_dtype : bool Notes ----- The default implementation is True if 1. ``cls.construct_f...
Auxiliary function for :meth:`str.cat` Parameters ---------- list_of_columns : list of numpy arrays List of arrays to be concatenated with sep; these arrays may not contain NaNs! sep : string The separator string for concatenating the columns Returns ------- nd.arra...
def cat_core(list_of_columns, sep): """ Auxiliary function for :meth:`str.cat` Parameters ---------- list_of_columns : list of numpy arrays List of arrays to be concatenated with sep; these arrays may not contain NaNs! sep : string The separator string for concatenating ...
Count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the :class:`~pandas.Series`. Parameters ---------- pat : str Valid regular expression. flags ...
def str_count(arr, pat, flags=0): """ Count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the :class:`~pandas.Series`. Parameters ---------- pat : st...
Test if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters ---------- pat : str Character sequence or regular expression. case : bool,...
def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): """ Test if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters --------...
Test if the start of each string element matches a pattern. Equivalent to :meth:`str.startswith`. Parameters ---------- pat : str Character sequence. Regular expressions are not accepted. na : object, default NaN Object shown if element tested is not a string. Returns ----...
def str_startswith(arr, pat, na=np.nan): """ Test if the start of each string element matches a pattern. Equivalent to :meth:`str.startswith`. Parameters ---------- pat : str Character sequence. Regular expressions are not accepted. na : object, default NaN Object shown if ...
Test if the end of each string element matches a pattern. Equivalent to :meth:`str.endswith`. Parameters ---------- pat : str Character sequence. Regular expressions are not accepted. na : object, default NaN Object shown if element tested is not a string. Returns ------- ...
def str_endswith(arr, pat, na=np.nan): """ Test if the end of each string element matches a pattern. Equivalent to :meth:`str.endswith`. Parameters ---------- pat : str Character sequence. Regular expressions are not accepted. na : object, default NaN Object shown if elemen...
r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a character sequence or regular expression. .. versionadded:: 0.20.0 ...
def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a charact...
Duplicate each string in the Series or Index. Parameters ---------- repeats : int or sequence of int Same value for all (int) or different value per (sequence). Returns ------- Series or Index of object Series or Index of repeated string objects specified by input param...
def str_repeat(arr, repeats): """ Duplicate each string in the Series or Index. Parameters ---------- repeats : int or sequence of int Same value for all (int) or different value per (sequence). Returns ------- Series or Index of object Series or Index of repeated strin...
Determine if each string matches a regular expression. Parameters ---------- pat : str Character sequence or regular expression. case : bool, default True If True, case sensitive. flags : int, default 0 (no flags) re module flags, e.g. re.IGNORECASE. na : default NaN ...
def str_match(arr, pat, case=True, flags=0, na=np.nan): """ Determine if each string matches a regular expression. Parameters ---------- pat : str Character sequence or regular expression. case : bool, default True If True, case sensitive. flags : int, default 0 (no flags) ...
Used in both extract_noexpand and extract_frame
def _groups_or_na_fun(regex): """Used in both extract_noexpand and extract_frame""" 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...
Find groups in each string in the Series using passed regular expression. This function is called from str_extract(expand=False), and can return Series, DataFrame, or Index.
def _str_extract_noexpand(arr, pat, flags=0): """ Find groups in each string in the Series using passed regular expression. This function is called from str_extract(expand=False), and can return Series, DataFrame, or Index. """ from pandas import DataFrame, Index regex = re.compile(pat...
For each subject string in the Series, extract groups from the first match of regular expression pat. This function is called from str_extract(expand=True), and always returns a DataFrame.
def _str_extract_frame(arr, pat, flags=0): """ For each subject string in the Series, extract groups from the first match of regular expression pat. This function is called from str_extract(expand=True), and always returns a DataFrame. """ from pandas import DataFrame regex = re.compile(pa...
r""" Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression `pat`. Parameters ---------- pat : str Regular expression pattern with capturing groups. flags : int, default 0...
def str_extract(arr, pat, flags=0, expand=True): r""" Extract capture groups in the regex `pat` as columns in a DataFrame. For each subject string in the Series, extract groups from the first match of regular expression `pat`. Parameters ---------- pat : str Regular expression patt...
r""" For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level='match') is the same as extract(pat). .. versionadded:: 0.18.0 Parameters ---------- pat : st...
def str_extractall(arr, pat, flags=0): r""" For each subject string in the Series, extract groups from all matches of regular expression pat. When each subject string in the Series has exactly one match, extractall(pat).xs(0, level='match') is the same as extract(pat). .. versionadded:: 0.18.0 ...
Split each string in the Series by sep and return a DataFrame of dummy/indicator variables. Parameters ---------- sep : str, default "|" String to split on. Returns ------- DataFrame Dummy variables corresponding to values of the Series. See Also -------- get_d...
def str_get_dummies(arr, sep='|'): """ Split each string in the Series by sep and return a DataFrame of dummy/indicator variables. Parameters ---------- sep : str, default "|" String to split on. Returns ------- DataFrame Dummy variables corresponding to values of t...
Find all occurrences of pattern or regular expression in the Series/Index. Equivalent to applying :func:`re.findall` to all the elements in the Series/Index. Parameters ---------- pat : str Pattern or regular expression. flags : int, default 0 Flags from ``re`` module, e.g. `re...
def str_findall(arr, pat, flags=0): """ Find all occurrences of pattern or regular expression in the Series/Index. Equivalent to applying :func:`re.findall` to all the elements in the Series/Index. Parameters ---------- pat : str Pattern or regular expression. flags : int, defa...
Return indexes in each strings in the Series/Index where the substring is fully contained between [start:end]. Return -1 on failure. Parameters ---------- sub : str Substring being searched. start : int Left edge index. end : int Right edge index. side : {'left', 'ri...
def str_find(arr, sub, start=0, end=None, side='left'): """ Return indexes in each strings in the Series/Index where the substring is fully contained between [start:end]. Return -1 on failure. Parameters ---------- sub : str Substring being searched. start : int Left edge in...
Pad strings in the Series/Index up to width. Parameters ---------- width : int Minimum width of resulting string; additional characters will be filled with character defined in `fillchar`. side : {'left', 'right', 'both'}, default 'left' Side from which to fill resulting string....
def str_pad(arr, width, side='left', fillchar=' '): """ Pad strings in the Series/Index up to width. Parameters ---------- width : int Minimum width of resulting string; additional characters will be filled with character defined in `fillchar`. side : {'left', 'right', 'both'}, ...
Slice substrings from each element in the Series or Index. Parameters ---------- start : int, optional Start position for slice operation. stop : int, optional Stop position for slice operation. step : int, optional Step size for slice operation. Returns ------- ...
def str_slice(arr, start=None, stop=None, step=None): """ Slice substrings from each element in the Series or Index. Parameters ---------- start : int, optional Start position for slice operation. stop : int, optional Stop position for slice operation. step : int, optional ...
Replace a positional slice of a string with another value. Parameters ---------- start : int, optional Left index position to use for the slice. If not specified (None), the slice is unbounded on the left, i.e. slice from the start of the string. stop : int, optional Rig...
def str_slice_replace(arr, start=None, stop=None, repl=None): """ Replace a positional slice of a string with another value. Parameters ---------- start : int, optional Left index position to use for the slice. If not specified (None), the slice is unbounded on the left, i.e. slice ...
Strip whitespace (including newlines) from each string in the Series/Index. Parameters ---------- to_strip : str or unicode side : {'left', 'right', 'both'}, default 'both' Returns ------- Series or Index
def str_strip(arr, to_strip=None, side='both'): """ Strip whitespace (including newlines) from each string in the Series/Index. Parameters ---------- to_strip : str or unicode side : {'left', 'right', 'both'}, default 'both' Returns ------- Series or Index """ if side =...
r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- width : int Maximum line width. expand_tabs : bool, opt...
def str_wrap(arr, width, **kwargs): r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- width : int Maximum...
Extract element from each component at specified position. Extract element from lists, tuples, or strings in each element in the Series/Index. Parameters ---------- i : int Position of element to extract. Returns ------- Series or Index Examples -------- >>> s = p...
def str_get(arr, i): """ Extract element from each component at specified position. Extract element from lists, tuples, or strings in each element in the Series/Index. Parameters ---------- i : int Position of element to extract. Returns ------- Series or Index Ex...
Decode character string in the Series/Index using indicated encoding. Equivalent to :meth:`str.decode` in python2 and :meth:`bytes.decode` in python3. Parameters ---------- encoding : str errors : str, optional Returns ------- Series or Index
def str_decode(arr, encoding, errors="strict"): """ Decode character string in the Series/Index using indicated encoding. Equivalent to :meth:`str.decode` in python2 and :meth:`bytes.decode` in python3. Parameters ---------- encoding : str errors : str, optional Returns -------...
Encode character string in the Series/Index using indicated encoding. Equivalent to :meth:`str.encode`. Parameters ---------- encoding : str errors : str, optional Returns ------- encoded : Series/Index of objects
def str_encode(arr, encoding, errors="strict"): """ Encode character string in the Series/Index using indicated encoding. Equivalent to :meth:`str.encode`. Parameters ---------- encoding : str errors : str, optional Returns ------- encoded : Series/Index of objects """ ...
Copy a docstring from another source function (if present)
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
Auxiliary function for :meth:`str.cat`. Turn potentially mixed input into a list of Series (elements without an index must match the length of the calling Series/Index). Parameters ---------- others : Series, Index, DataFrame, np.ndarray, list-like or list-like of ob...
def _get_series_list(self, others, ignore_index=False): """ Auxiliary function for :meth:`str.cat`. Turn potentially mixed input into a list of Series (elements without an index must match the length of the calling Series/Index). Parameters ---------- others : Se...
Concatenate strings in the Series/Index with given separator. If `others` is specified, this function concatenates the Series/Index and elements of `others` element-wise. If `others` is not passed, then all values in the Series/Index are concatenated into a single string with a given `s...
def cat(self, others=None, sep=None, na_rep=None, join=None): """ Concatenate strings in the Series/Index with given separator. If `others` is specified, this function concatenates the Series/Index and elements of `others` element-wise. If `others` is not passed, then all values...
Pad strings in the Series/Index by prepending '0' characters. Strings in the Series/Index are padded with '0' characters on the left of the string to reach a total string length `width`. Strings in the Series/Index with length greater or equal to `width` are unchanged. Paramet...
def zfill(self, width): """ Pad strings in the Series/Index by prepending '0' characters. Strings in the Series/Index are padded with '0' characters on the left of the string to reach a total string length `width`. Strings in the Series/Index with length greater or equal to `wi...
Return the Unicode normal form for the strings in the Series/Index. For more information on the forms, see the :func:`unicodedata.normalize`. Parameters ---------- form : {'NFC', 'NFKC', 'NFD', 'NFKD'} Unicode form Returns ------- normalized ...
def normalize(self, form): """ Return the Unicode normal form for the strings in the Series/Index. For more information on the forms, see the :func:`unicodedata.normalize`. Parameters ---------- form : {'NFC', 'NFKC', 'NFD', 'NFKD'} Unicode form ...
Returns system information as a dict
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(" "), stdout=subpr...
Yields all GroupBy member defs for DataFrame/Series names in whitelist. Parameters ---------- base : class base class klass : class class where members are defined. Should be Series or DataFrame whitelist : list list of names of klass methods to be constructed R...
def whitelist_method_generator(base, klass, whitelist): """ Yields all GroupBy member defs for DataFrame/Series names in whitelist. Parameters ---------- base : class base class klass : class class where members are defined. Should be Series or DataFrame whitelist : ...
Dispatch to apply.
def _dispatch(name, *args, **kwargs): """ Dispatch to apply. """ 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) ...
Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on
def _gotitem(self, key, ndim, subset=None): """ Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on ...
Convert bytes and non-string into Python 3 str
def to_str(s): """ Convert bytes and non-string into Python 3 str """ if isinstance(s, bytes): s = s.decode('utf-8') elif not isinstance(s, str): s = str(s) return s
Bind the name/qualname attributes of the function
def set_function_name(f, name, cls): """ Bind the name/qualname attributes of the function """ f.__name__ = name f.__qualname__ = '{klass}.{name}'.format( klass=cls.__name__, name=name) f.__module__ = cls.__module__ return f
Raise exception with existing traceback. If traceback is not passed, uses sys.exc_info() to get traceback.
def raise_with_traceback(exc, traceback=Ellipsis): """ Raise exception with existing traceback. If traceback is not passed, uses sys.exc_info() to get traceback. """ if traceback == Ellipsis: _, _, traceback = sys.exc_info() raise exc.with_traceback(traceback)
converts a style_dict to an openpyxl style object Parameters ---------- style_dict : style dictionary to convert
def _convert_to_style(cls, style_dict): """ converts a style_dict to an openpyxl style object Parameters ---------- style_dict : style dictionary to convert """ from openpyxl.style import Style xls_style = Style() for key, value in style_dict.item...
Convert a style_dict to a set of kwargs suitable for initializing or updating-on-copy an openpyxl v2 style object Parameters ---------- style_dict : dict A dict with zero or more of the following keys (or their synonyms). 'font' 'fill' ...
def _convert_to_style_kwargs(cls, style_dict): """ Convert a style_dict to a set of kwargs suitable for initializing or updating-on-copy an openpyxl v2 style object Parameters ---------- style_dict : dict A dict with zero or more of the following keys (or thei...
Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' 'indexed' 'auto' 'theme' ...
def _convert_to_color(cls, color_spec): """ Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' ...
Convert ``font_dict`` to an openpyxl v2 Font object Parameters ---------- font_dict : dict A dict with zero or more of the following keys (or their synonyms). 'name' 'size' ('sz') 'bold' ('b') 'italic' ('i') ...
def _convert_to_font(cls, font_dict): """ Convert ``font_dict`` to an openpyxl v2 Font object Parameters ---------- font_dict : dict A dict with zero or more of the following keys (or their synonyms). 'name' 'size' ('sz') ...
Convert ``fill_dict`` to an openpyxl v2 Fill object Parameters ---------- fill_dict : dict A dict with one or more of the following keys (or their synonyms), 'fill_type' ('patternType', 'patterntype') 'start_color' ('fgColor', 'fgcolor') ...
def _convert_to_fill(cls, fill_dict): """ Convert ``fill_dict`` to an openpyxl v2 Fill object Parameters ---------- fill_dict : dict A dict with one or more of the following keys (or their synonyms), 'fill_type' ('patternType', 'patterntype') ...
Convert ``side_spec`` to an openpyxl v2 Side object Parameters ---------- side_spec : str, dict A string specifying the border style, or a dict with zero or more of the following keys (or their synonyms). 'style' ('border_style') 'color' ...
def _convert_to_side(cls, side_spec): """ Convert ``side_spec`` to an openpyxl v2 Side object Parameters ---------- side_spec : str, dict A string specifying the border style, or a dict with zero or more of the following keys (or their synonyms). ...
Convert ``border_dict`` to an openpyxl v2 Border object Parameters ---------- border_dict : dict A dict with zero or more of the following keys (or their synonyms). 'left' 'right' 'top' 'bottom' 'diagonal...
def _convert_to_border(cls, border_dict): """ Convert ``border_dict`` to an openpyxl v2 Border object Parameters ---------- border_dict : dict A dict with zero or more of the following keys (or their synonyms). 'left' 'right' ...
construct and return a row or column based frame apply object
def frame_apply(obj, func, axis=0, broadcast=None, raw=False, reduce=None, result_type=None, ignore_failures=False, args=None, kwds=None): """ construct and return a row or column based frame apply object """ axis = obj._get_axis_number(axis) if axis == 0: ...
we have an empty result; at least 1 axis is 0 we will try to apply the function to an empty series in order to see if this is a reduction function
def apply_empty_result(self): """ we have an empty result; at least 1 axis is 0 we will try to apply the function to an empty series in order to see if this is a reduction function """ # we are not asked to reduce or infer reduction # so just return a copy of th...
compute the results
def get_result(self): """ compute the results """ # 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(self.columns) == ...
apply to the values as a numpy array
def apply_raw(self): """ apply to the values as a numpy array """ 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 ==...
return the results for the rows
def wrap_results_for_axis(self): """ return the results for the rows """ 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 columns
def wrap_results_for_axis(self): """ return the results for the columns """ 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 isi...
infer the results to the same shape as the input object
def infer_to_same_shape(self): """ infer the results to the same shape as the input object """ results = self.results result = self.obj._constructor(data=results) result = result.T # set the index result.index = self.res_index # infer dtypes result = re...
Numpy version of itertools.product. Sometimes faster (for large inputs)... Parameters ---------- X : list-like of list-likes Returns ------- product : list of ndarrays Examples -------- >>> cartesian_product([list('ABC'), [1, 2]]) [array(['A', 'A', 'B', 'B', 'C', 'C'], dty...
def cartesian_product(X): """ Numpy version of itertools.product. Sometimes faster (for large inputs)... Parameters ---------- X : list-like of list-likes Returns ------- product : list of ndarrays Examples -------- >>> cartesian_product([list('ABC'), [1, 2]]) [arr...
Returns the url without the s3:// part
def _strip_schema(url): """Returns the url without the s3:// part""" result = parse_url(url, allow_fragments=False) return result.netloc + result.path
Preview version of Xception network. Not tested yet - use at own risk. No pretrained model yet.
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), ConvSkip(k*32, k*91), ] for ...
Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module. Args: opt_fn (Optimizer): the torch optimizer function to use emb_sz (int): embedding size n_hid (int): number of hidden inputs n_layers (int): number of hidden layers ...
def get_model(self, opt_fn, emb_sz, n_hid, n_layers, **kwargs): """ Method returns a RNN_Learner object, that wraps an instance of the RNN_Encoder module. Args: opt_fn (Optimizer): the torch optimizer function to use emb_sz (int): embedding size n_hid (int): number o...
Method used to instantiate a LanguageModelData object that can be used for a supported nlp task. Args: path (str): the absolute path in which temporary model data will be saved field (Field): torchtext field train (str): file location of the training data ...
def from_text_files(cls, path, field, train, validation, test=None, bs=64, bptt=70, **kwargs): """ Method used to instantiate a LanguageModelData object that can be used for a supported nlp task. Args: path (str): the absolute path in which temporary model data will be saved ...
Return list of files in `path` that have a suffix in `extensions`; optionally `recurse`.
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 = [] for i,(p,d,f) in enumerate(os.wa...
Load an empty `DataBunch` from the exported file in `path/fname` with optional `tfms`.
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()
Apply `processor` or `self.processor` to `self`.
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) return self
Apply `processor` or `self.processor` to `item`.
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 = p.process_one(item) return item
Reconstruct one of the underlying item for its data `t`.
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)
Create a new `ItemList` from `items`, keeping the same attributes.
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} kwargs = {**copy_d, **kwargs} ...
Create an `ItemList` in `path` from the filenames that have a suffix in `extensions`. `recurse` determines if we search subfolders.
def from_folder(cls, path:PathOrStr, extensions:Collection[str]=None, recurse:bool=True, include:Optional[Collection[str]]=None, processor:PreProcessors=None, **kwargs)->'ItemList': """Create an `ItemList` in `path` from the filenames that have a suffix in `extensions`. `recurse` det...
Create an `ItemList` in `path` from the inputs in the `cols` of `df`.
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 inputs.isna().sum().sum() == 0, f"You have NaN v...
Create an `ItemList` in `path` from the inputs in the `cols` of `path/csv_name`
def from_csv(cls, path:PathOrStr, csv_name:str, cols:IntsOrStrs=0, delimiter:str=None, header:str='infer', processor:PreProcessors=None, **kwargs)->'ItemList': """Create an `ItemList` in `path` from the inputs in the `cols` of `path/csv_name`""" df = pd.read_csv(Path(path)/csv_name, del...
Use only a sample of `sample_pct`of the full dataset and an optional `seed`.
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)) cut = int(sample_pct * len(self)) ...
Save `self.items` to `fn` in `self.path`.
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()])
Only keep elements for which `func` returns `True`.
def filter_by_func(self, func:Callable)->'ItemList': "Only keep elements for which `func` returns `True`." self.items = array([o for o in self.items if func(o)]) return self
Only keep filenames in `include` folder or reject the ones in `exclude`.
def filter_by_folder(self, include=None, exclude=None): "Only keep filenames in `include` folder or reject the ones in `exclude`." include,exclude = listify(include),listify(exclude) def _inner(o): if isinstance(o, Path): n = o.relative_to(self.path).parts[0] else: n = o....
Keep random sample of `items` with probability `p` and an optional `seed`.
def filter_by_rand(self, p:float, seed:int=None): "Keep random sample of `items` with probability `p` and an optional `seed`." if seed is not None: np.random.seed(seed) return self.filter_by_func(lambda o: rand_bool(p))
Don't split the data and create an empty validation set.
def split_none(self): "Don't split the data and create an empty validation set." val = self[[]] val.ignore_empty = True return self._split(self.path, self, val)
Split the data between `train` and `valid`.
def split_by_list(self, train, valid): "Split the data between `train` and `valid`." return self._split(self.path, train, valid)