INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Check whether the provided array or dtype is of a boolean dtype.
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.
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.
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.
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.
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.
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.
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.
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.
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
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 )
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.
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 *
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
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
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 )
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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 ).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 ).
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.
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.
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.
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.
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.
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 border ( borders ) alignment number_format protection Returns ------- style_kwargs:...
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 tint index type Returns ------- color: openpyxl. styles. Color
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 ) underline ( u ) strikethrough ( strike ) color vertAlign ( vertalign ) charset scheme family outline shadow condense Return...
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 ) end_color ( bgColor bgcolor ) or one or more of the following keys ( or their synonyms ). type (...
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 Returns ------- side: openpyxl. styles. Side
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 diagonal_direction vertical horizontal diagonalUp ( diagonalup ) diagonalDown ( diagonaldown ) outline Returns ------- border: ...
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: ...
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) == ...
we have an empty result ; at least 1 axis is 0
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...
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 )...
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.
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.
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)
Split the data between train_idx and valid_idx.
def split_by_idxs(self, train_idx, valid_idx): "Split the data between `train_idx` and `valid_idx`." return self.split_by_list(self[train_idx], self[valid_idx])
Split the data according to the indexes in valid_idx.
def split_by_idx(self, valid_idx:Collection[int])->'ItemLists': "Split the data according to the indexes in `valid_idx`." #train_idx = [i for i in range_of(self.items) if i not in valid_idx] train_idx = np.setdiff1d(arange_of(self.items), valid_idx) return self.split_by_idxs(train_idx, v...
Split the data depending on the folder ( train or valid ) in which the filenames are.
def split_by_folder(self, train:str='train', valid:str='valid')->'ItemLists': "Split the data depending on the folder (`train` or `valid`) in which the filenames are." return self.split_by_idxs(self._get_by_folder(train), self._get_by_folder(valid))
Split the items randomly by putting valid_pct in the validation set optional seed can be passed.
def split_by_rand_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists': "Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed." if valid_pct==0.: return self.split_none() if seed is not None: np.random.seed(seed) rand_idx = np.random....
Split the items into train set with size train_size * n and valid set with size valid_size * n.
def split_subsets(self, train_size:float, valid_size:float, seed=None) -> 'ItemLists': "Split the items into train set with size `train_size * n` and valid set with size `valid_size * n`." assert 0 < train_size < 1 assert 0 < valid_size < 1 assert train_size + valid_size <= 1. if...
Split the data by result of func ( which returns True for validation set ).
def split_by_valid_func(self, func:Callable)->'ItemLists': "Split the data by result of `func` (which returns `True` for validation set)." valid_idx = [i for i,o in enumerate(self.items) if func(o)] return self.split_by_idx(valid_idx)
Split the data by using the names in valid_names for validation.
def split_by_files(self, valid_names:'ItemList')->'ItemLists': "Split the data by using the names in `valid_names` for validation." if isinstance(self.items[0], Path): return self.split_by_valid_func(lambda o: o.name in valid_names) else: return self.split_by_valid_func(lambda o: os.path.basenam...
Split the data by using the names in fname for the validation set. path will override self. path.
def split_by_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists': "Split the data by using the names in `fname` for the validation set. `path` will override `self.path`." path = Path(ifnone(path, self.path)) valid_names = loadtxt_str(path/fname) return self.split_by_files...
Split the data from the col in the dataframe in self. inner_df.
def split_from_df(self, col:IntsOrStrs=2): "Split the data from the `col` in the dataframe in `self.inner_df`." valid_idx = np.where(self.inner_df.iloc[:,df_names_to_idx(col, self.inner_df)])[0] return self.split_by_idx(valid_idx)
Return label_cls or guess one from the first element of labels.
def get_label_cls(self, labels, label_cls:Callable=None, label_delim:str=None, **kwargs): "Return `label_cls` or guess one from the first element of `labels`." if label_cls is not None: return label_cls if self.label_cls is not None: return self.label_cls if label_...