text
stringlengths
81
112k
A special case for _generate_range_overflow_safe where `periods * stride` can be calculated without overflowing int64 bounds. def _generate_range_overflow_safe_signed(endpoint, periods, stride, side): """ A special case for _generate_range_overflow_safe where `periods * stride` can be calculated withou...
Context manager for temporarily setting a locale. Parameters ---------- new_locale : str or tuple A string of the form <language_country>.<encoding>. For example to set the current locale to US English with a UTF8 encoding, you would pass "en_US.UTF-8". lc_var : int, default `lo...
Check to see if we can set a locale, and subsequently get the locale, without raising an Exception. Parameters ---------- lc : str The locale to attempt to set. lc_var : int, default `locale.LC_ALL` The category of the locale being set. Returns ------- is_valid : bool ...
Return a list of normalized locales that do not throw an ``Exception`` when set. Parameters ---------- locales : str A string where each locale is separated by a newline. normalize : bool Whether to call ``locale.normalize`` on each locale. Returns ------- valid_locales...
Get all the locales that are available on the system. Parameters ---------- prefix : str If not ``None`` then return only those locales with the prefix provided. For example to get all English language locales (those that start with ``"en"``), pass ``prefix="en"``. normalize : b...
Ensure that an array object has a float dtype if possible. Parameters ---------- arr : array-like The array whose data type we want to enforce as float. Returns ------- float_arr : The original array cast to the float dtype if possible. Otherwise, the original array is ...
Ensure that an array-like object is a Categorical (if not already). Parameters ---------- arr : array-like The array that we want to convert into a Categorical. Returns ------- cat_arr : The original array cast as a Categorical. If it already is a Categorical, we return a...
Ensure that an dtype array of some integer dtype has an int64 dtype if possible If it's not possible, potentially because of overflow, convert the array to float64 instead. Parameters ---------- arr : array-like The array whose data type we want to enforce. copy: boolean ...
evaluate if the tipo is a subclass of the klasses and not a datetimelike def classes_and_not_datetimelike(*klasses): """ evaluate if the tipo is a subclass of the klasses and not a datetimelike """ return lambda tipo: (issubclass(tipo, klasses) and not issubclass(tipo, ...
Check whether an array-like is a 1-D pandas sparse array. Check that the one-dimensional array-like is a pandas sparse array. Returns True if it is a pandas sparse array, not another type of sparse array. Parameters ---------- arr : array-like Array-like to check. Returns ----...
Check whether an array-like is a scipy.sparse.spmatrix instance. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a scipy.sparse.spmatrix instance. Notes ----- If scipy is not installed, this f...
Check if obj or all elements of list-like is DateOffset Parameters ---------- arr_or_obj : object Returns ------- boolean Whether the object is a DateOffset or listlike of DatetOffsets Examples -------- >>> is_offsetlike(pd.DateOffset(days=1)) True >>> is_offsetlik...
Check whether an array-like is a periodical index. .. deprecated:: 0.24.0 Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical index. Examples -------- >>> is_period([1, 2, 3]) ...
Check whether the provided array or dtype is of the string 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 string dtype. Examples -------- >>> is_string_dtype(st...
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 -------- ...
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_...
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...
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...
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 ...
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...
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...
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 ...
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...
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...
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...
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 : ...
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...
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 ------...
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...
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...
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 ...
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 ...
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 dtyp...
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 de...
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....
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...
*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...
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...
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...
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 ------...
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_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 ...
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...
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 ...
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,...
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 ----...
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 ------- ...
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 ...
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...
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 ...
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): ...
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 expressio...
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 ...
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...
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...
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...
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...
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...
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....
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 ------- ...
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...
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 (in...
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...
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...
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="...
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 char...
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...
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...
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...
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 ...
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(" "), ...
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...
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....
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-...
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 == Ellips...
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 diction...
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' ...
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' ...
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') ...
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') ...
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' ...
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...
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 ...
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 ...
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 ...
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: mix...
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 ...
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...
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 = s...
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...
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(...
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 ...
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 ...
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`; option...
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()