INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Checkboxes are hidden when inside of a RadioGroup as a selection of the Radio button is an implicit selection of the Checkbox. As such we have to manually check any checkbox as needed.
def handleImplicitCheck(self): """ Checkboxes are hidden when inside of a RadioGroup as a selection of the Radio button is an implicit selection of the Checkbox. As such, we have to manually "check" any checkbox as needed. """ for button, widget in zip(self.radioBut...
Instantiate the Gooey Widgets that are used within the RadioGroup
def createWidgets(self): """ Instantiate the Gooey Widgets that are used within the RadioGroup """ from gooey.gui.components import widgets return [getattr(widgets, item['type'])(self, item) for item in getin(self.widgetInfo, ['data', 'widgets'], [])]
Verify user input and kick off the client s program if valid
def onStart(self, *args, **kwarg): """ Verify user input and kick off the client's program if valid """ with transactUI(self): config = self.navbar.getActiveConfig() config.resetErrors() if config.isValid(): self.clientRunner.ru...
Return the user to the settings screen for further editing
def onEdit(self): """Return the user to the settings screen for further editing""" with transactUI(self): if self.buildSpec['poll_external_updates']: self.fetchExternalUpdates() self.showSettings()
Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program
def buildCliString(self): """ Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program """ config = self.navbar.getActiveConfig() group = self.buildSpec['widgets'][self.navbar.getSelectedGro...
Display the appropriate screen based on the success/ fail of the host program
def onComplete(self, *args, **kwargs): """ Display the appropriate screen based on the success/fail of the host program """ with transactUI(self): if self.clientRunner.was_success(): if self.buildSpec.get('return_to_config', False): ...
!Experimental! Calls out to the client code requesting seed values to use in the UI !Experimental!
def fetchExternalUpdates(self): """ !Experimental! Calls out to the client code requesting seed values to use in the UI !Experimental! """ seeds = seeder.fetchDynamicProperties( self.buildSpec['target'], self.buildSpec['encoding'] ...
Chooses the appropriate layout navigation component based on user prefs
def buildNavigation(self): """ Chooses the appropriate layout navigation component based on user prefs """ if self.buildSpec['navigation'] == constants.TABBED: navigation = Tabbar(self, self.buildSpec, self.configs) else: navigation = Sidebar(self, ...
Choose the best font face available given the user options
def getFontFace(self): """Choose the best font face available given the user options""" userFace = self.buildSpec['terminal_font_family'] or self.defaultFont.GetFaceName() return ('' if self.buildSpec['monospace_display'] else userFace)
Reads the stdout of process and forwards lines and progress to any interested subscribers
def _forward_stdout(self, process): ''' Reads the stdout of `process` and forwards lines and progress to any interested subscribers ''' while True: line = process.stdout.readline() if not line: break pub.send_message(ev...
Finds progress information in the text using the user - supplied regex and calculation instructions
def _extract_progress(self, text): ''' Finds progress information in the text using the user-supplied regex and calculation instructions ''' # monad-ish dispatch to avoid the if/else soup find = partial(re.search, string=text.strip().decode(self.encoding)) ...
Calculates the final progress value found by the regex
def _calculate_progress(self, match): ''' Calculates the final progress value found by the regex ''' if not self.progress_expr: return safe_float(match.group(1)) else: return self._eval_progress(match)
Runs the user - supplied progress calculation rule
def _eval_progress(self, match): ''' Runs the user-supplied progress calculation rule ''' _locals = {k: safe_float(v) for k, v in match.groupdict().items()} if "x" not in _locals: _locals["x"] = [safe_float(x) for x in match.groups()] try: ...
Hide/ show configuration panels based on the currently selected option in the sidebar
def swapConfigPanels(self, event): """Hide/show configuration panels based on the currently selected option in the sidebar """ for id, panel in enumerate(self.configPanels): panel.Hide() self.activeSelection = event.Selection self.configPanels[event.Selection]....
value disable_animation = False: param args:: param kwargs:: return:
def updateProgressBar(self, *args, **kwargs): ''' value, disable_animation=False :param args: :param kwargs: :return: ''' value = kwargs.get('progress') pb = self.progress_bar if value is None: return if value < 0: ...
Decorator for client code s main function. Serializes argparse data to JSON for use with the Gooey front end
def Gooey(f=None, advanced=True, language='english', auto_start=False, # TODO: add this to the docs. Used to be `show_config=True` target=None, program_name=None, program_description=None, default_size=(610, 530), use_legacy_titles...
Sends a gooey - seed - ui request to the client program it retrieve dynamically generated defaults with which to seed the UI
def fetchDynamicProperties(target, encoding): """ Sends a gooey-seed-ui request to the client program it retrieve dynamically generated defaults with which to seed the UI """ cmd = '{} {}'.format(target, 'gooey-seed-ui --ignore-gooey') proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, s...
Messily builds the ( potentially ) nested and grouped layout Note! Mutates self. reifiedWidgets in place with the widgets as they re instantiated! I cannot figure out how to split out the creation of the widgets from their styling without WxPython violently exploding TODO: sort out the WX quirks and clean this up.
def makeGroup(self, parent, thissizer, group, *args): ''' Messily builds the (potentially) nested and grouped layout Note! Mutates `self.reifiedWidgets` in place with the widgets as they're instantiated! I cannot figure out how to split out the creation of the widgets from...
chunk the widgets up into groups based on their sizing hints
def chunkWidgets(self, group): ''' chunk the widgets up into groups based on their sizing hints ''' ui_groups = [] subgroup = [] for index, item in enumerate(group['items']): if getin(item, ['options', 'full_width'], False): ui_groups.append(subgroup) ...
Convert a JSON description of a widget into a WxObject
def reifyWidget(self, parent, item): ''' Convert a JSON description of a widget into a WxObject ''' from gooey.gui.components import widgets widgetClass = getattr(widgets, item['type']) return widgetClass(parent, item)
Recursively extract argument groups and associated actions from ParserGroup objects
def extract_groups(action_group): ''' Recursively extract argument groups and associated actions from ParserGroup objects ''' return { 'name': action_group.title, 'description': action_group.description, 'items': [action for action in action_group._group_actions ...
_actions possessing the required flag and not implicitly optional through nargs being * or ?
def is_required(action): ''' _actions possessing the `required` flag and not implicitly optional through `nargs` being '*' or '?' ''' return not isinstance(action, _SubParsersAction) and ( action.required == True and action.nargs not in ['*', '?'])
actions which are general store instructions. e. g. anything which has an argument style like: $ script. py - f myfilename. txt
def is_standard(action): """ actions which are general "store" instructions. e.g. anything which has an argument style like: $ script.py -f myfilename.txt """ boolean_actions = ( _StoreConstAction, _StoreFalseAction, _StoreTrueAction ) return (not action.choices ...
_actions which are either storeconst store_bool etc..
def is_flag(action): """ _actions which are either storeconst, store_bool, etc.. """ action_types = [_StoreTrueAction, _StoreFalseAction, _StoreConstAction] return any(list(map(lambda Action: isinstance(action, Action), action_types)))
Returns str ( option_string * DropDown Value ) e. g. - vvvvv
def counter(metatdata, value): ''' Returns str(option_string * DropDown Value) e.g. -vvvvv ''' if not str(value).isdigit(): return None arg = str(metatdata['commands'][0]).replace('-', '') repeated_args = arg * int(value) return '-' + repeated_args
Open and return the supplied json file
def load(language_dir, filename, encoding): ''' Open and return the supplied json file ''' global _DICTIONARY try: json_file = filename + '.json' with io.open(os.path.join(language_dir, json_file), 'r', encoding=encoding) as f: _DICTIONARY = json.load(f) except IOError: raise IOError('...
returns the value in a nested dict
def getin(m, path, default=None): """returns the value in a nested dict""" keynotfound = ':com.gooey-project/not-found' result = reduce(lambda acc, val: acc.get(val, {keynotfound: None}), path, m) # falsey values like 0 would incorrectly trigger the default to be returned # so the keynotfound v...
Copy - on - write associates a value in a dict
def assoc(m, key, val): """Copy-on-write associates a value in a dict""" cpy = deepcopy(m) cpy[key] = val return cpy
Copy - on - write associates a value in a nested dict
def associn(m, path, value): """ Copy-on-write associates a value in a nested dict """ def assoc_recursively(m, path, value): if not path: return value p = path[0] return assoc(m, p, assoc_recursively(m.get(p,{}), path[1:], value)) return assoc_recursively(m, path,...
Merge all maps left to right
def merge(*maps): """Merge all maps left to right""" copies = map(deepcopy, maps) return reduce(lambda acc, val: acc.update(val) or acc, copies)
Return first occurrence matching f otherwise None
def findfirst(f, coll): """Return first occurrence matching f, otherwise None""" result = list(dropwhile(f, coll)) return result[0] if result else None
Generates the input_tensor that minimizes the weighted losses. This function is intended for advanced use cases where a custom loss is desired.
def visualize_activation_with_losses(input_tensor, losses, wrt_tensor=None, seed_input=None, input_range=(0, 255), **optimizer_params): """Generates the `input_tensor` that minimizes the weighted `losses`. This function is intended for advanc...
Generates the model input that maximizes the output of all filter_indices in the given layer_idx.
def visualize_activation(model, layer_idx, filter_indices=None, wrt_tensor=None, seed_input=None, input_range=(0, 255), backprop_modifier=None, grad_modifier=None, act_max_weight=1, lp_norm_weight=10, tv_weight=10, **opt...
Uses RMSProp to compute step from gradients.
def _rmsprop(self, grads, cache=None, decay_rate=0.95): """Uses RMSProp to compute step from gradients. Args: grads: numpy array of gradients. cache: numpy array of same shape as `grads` as RMSProp cache decay_rate: How fast to decay cache Returns: ...
Creates a random seed_input if None. Otherwise: - Ensures batch_size dim on provided seed_input. - Shuffle axis according to expected image_data_format.
def _get_seed_input(self, seed_input): """Creates a random `seed_input` if None. Otherwise: - Ensures batch_size dim on provided `seed_input`. - Shuffle axis according to expected `image_data_format`. """ desired_shape = (1, ) + K.int_shape(self.input_tensor)[1:] ...
Performs gradient descent on the input image with respect to defined losses.
def minimize(self, seed_input=None, max_iter=200, input_modifiers=None, grad_modifier=None, callbacks=None, verbose=True): """Performs gradient descent on the input image with respect to defined losses. Args: seed_input: An N-dim numpy array of shape: `(sam...
Orders the set of objs by line_nos
def order_by_line_nos(objs, line_nos): """Orders the set of `objs` by `line_nos` """ ordering = sorted(range(len(line_nos)), key=line_nos.__getitem__) return [objs[i] for i in ordering]
Import a module path and create an api doc from it
def to_md_file(string, filename, out_path="."): """Import a module path and create an api doc from it Args: string (str): string with line breaks to write to file. filename (str): filename without the .md out_path (str): The output directory """ md_file = "%s.md" % filename ...
Creates a src path string with line info for use as markdown link.
def get_src_path(self, obj, append_base=True): """Creates a src path string with line info for use as markdown link. """ path = getsourcefile(obj) if self.src_root not in path: # this can happen with e.g. # inlinefunc-wrapped functions if hasattr(obj, ...
Parse docstring ( parsed with getdoc ) according to Google - style formatting and convert to markdown. We support the following Google style syntax:
def doc2md(self, func): """Parse docstring (parsed with getdoc) according to Google-style formatting and convert to markdown. We support the following Google style syntax: Args, Kwargs: argname (type): text freeform text Returns, Yields: retna...
Takes a function ( or method ) and documents it.
def func2md(self, func, clsname=None, names=None, depth=3): """Takes a function (or method) and documents it. Args: clsname (str, optional): class name to prepend to funcname. depth (int, optional): number of ### to append to function name """ section = "#" * de...
Takes a class and creates markdown text to document its methods and variables.
def class2md(self, cls, depth=2): """Takes a class and creates markdown text to document its methods and variables. """ section = "#" * depth subsection = "#" * (depth + 2) clsname = cls.__name__ modname = cls.__module__ header = clsname path = self.get_s...
Takes an imported module object and create a Markdown string containing functions and classes.
def module2md(self, module): """Takes an imported module object and create a Markdown string containing functions and classes. """ modname = module.__name__ path = self.get_src_path(module, append_base=False) path = "[{}]({})".format(path, os.path.join(self.github_link, path)) ...
Searches for the nearest penultimate Conv or Pooling layer.
def _find_penultimate_layer(model, layer_idx, penultimate_layer_idx): """Searches for the nearest penultimate `Conv` or `Pooling` layer. Args: model: The `keras.models.Model` instance. layer_idx: The layer index within `model.layers`. penultimate_layer_idx: The pre-layer to `layer_idx`....
Generates an attention heatmap over the seed_input by using positive gradients of input_tensor with respect to weighted losses.
def visualize_saliency_with_losses(input_tensor, losses, seed_input, wrt_tensor=None, grad_modifier='absolute', keepdims=False): """Generates an attention heatmap over the `seed_input` by using positive gradients of `input_tensor` with respect to weighted `losses`. This function is intended for advanced us...
Generates an attention heatmap over the seed_input for maximizing filter_indices output in the given layer_idx.
def visualize_saliency(model, layer_idx, filter_indices, seed_input, wrt_tensor=None, backprop_modifier=None, grad_modifier='absolute', keepdims=False): """Generates an attention heatmap over the `seed_input` for maximizing `filter_indices` output in the given `layer_idx`. Args: ...
Generates a gradient based class activation map ( CAM ) by using positive gradients of input_tensor with respect to weighted losses.
def visualize_cam_with_losses(input_tensor, losses, seed_input, penultimate_layer, grad_modifier=None): """Generates a gradient based class activation map (CAM) by using positive gradients of `input_tensor` with respect to weighted `losses`. For details on grad-CAM, see the paper: [Grad-CAM: Why did yo...
Generates a gradient based class activation map ( grad - CAM ) that maximizes the outputs of filter_indices in layer_idx.
def visualize_cam(model, layer_idx, filter_indices, seed_input, penultimate_layer_idx=None, backprop_modifier=None, grad_modifier=None): """Generates a gradient based class activation map (grad-CAM) that maximizes the outputs of `filter_indices` in `layer_idx`. Args: ...
Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior.
def modify_model_backprop(model, backprop_modifier): """Creates a copy of model by modifying all activations to use a custom op to modify the backprop behavior. Args: model: The `keras.models.Model` instance. backprop_modifier: One of `{'guided', 'rectified'}` Returns: A copy of m...
Normalizes the output_tensor with respect to input_tensor dimensions. This makes regularizer weight factor more or less uniform across various input image dimensions.
def normalize(input_tensor, output_tensor): """Normalizes the `output_tensor` with respect to `input_tensor` dimensions. This makes regularizer weight factor more or less uniform across various input image dimensions. Args: input_tensor: An tensor of shape: `(samples, channels, image_dims...)` if `...
r Implements the N - dim version of function $$TV^ { \ beta } ( x ) = \ sum_ { whc } \ left ( \ left ( x ( h w + 1 c ) - x ( h w c ) \ right ) ^ { 2 } + \ left ( x ( h + 1 w c ) - x ( h w c ) \ right ) ^ { 2 } \ right ) ^ { \ frac { \ beta } { 2 }} $$ to return total variation for all images in the batch.
def build_loss(self): r"""Implements the N-dim version of function $$TV^{\beta}(x) = \sum_{whc} \left ( \left ( x(h, w+1, c) - x(h, w, c) \right )^{2} + \left ( x(h+1, w, c) - x(h, w, c) \right )^{2} \right )^{\frac{\beta}{2}}$$ to return total variation for all images in the batch. ...
Utility to find font file.
def _find_font_file(query): """Utility to find font file. """ return list(filter(lambda path: query.lower() in os.path.basename(path).lower(), fontman.findSystemFonts()))
Updates kwargs with dict of defaults
def add_defaults_to_kwargs(defaults, **kwargs): """Updates `kwargs` with dict of `defaults` Args: defaults: A dictionary of keys and values **kwargs: The kwargs to update. Returns: The updated kwargs. """ defaults = dict(defaults) defaults.update(kwargs) return defa...
Helper utility to retrieve the callable function associated with a string identifier.
def get_identifier(identifier, module_globals, module_name): """Helper utility to retrieve the callable function associated with a string identifier. Args: identifier: The identifier. Could be a string or function. module_globals: The global objects of the module. module_name: The modul...
Applies modifications to the model layers to create a new Graph. For example simply changing model. layers [ idx ]. activation = new activation does not change the graph. The entire graph needs to be updated with modified inbound and outbound tensors because of change in layer building function.
def apply_modifications(model, custom_objects=None): """Applies modifications to the model layers to create a new Graph. For example, simply changing `model.layers[idx].activation = new activation` does not change the graph. The entire graph needs to be updated with modified inbound and outbound tensors bec...
Creates a uniformly distributed random array with the given mean and std.
def random_array(shape, mean=128., std=20.): """Creates a uniformly distributed random array with the given `mean` and `std`. Args: shape: The desired shape mean: The desired mean (Default value = 128) std: The desired std (Default value = 20) Returns: Random numpy array of given `...
Looks up the layer index corresponding to layer_name from model.
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ ...
Utility function to scale the input_array to input_range throwing away high frequency artifacts.
def deprocess_input(input_array, input_range=(0, 255)): """Utility function to scale the `input_array` to `input_range` throwing away high frequency artifacts. Args: input_array: An N-dim numpy array. input_range: Specifies the input range as a `(min, max)` tuple to rescale the `input_array`. ...
Utility function to stitch images together with a margin.
def stitch_images(images, margin=5, cols=5): """Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is created when num...
Returns image shape in a backend agnostic manner.
def get_img_shape(img): """Returns image shape in a backend agnostic manner. Args: img: An image tensor of shape: `(channels, image_dims...)` if data_format='channels_first' or `(image_dims..., channels)` if data_format='channels_last'. Returns: Tuple containing image shape inf...
Utility function to load an image from disk.
def load_img(path, grayscale=False, target_size=None): """Utility function to load an image from disk. Args: path: The image file path. grayscale: True to convert to grayscale image (Default value = False) target_size: (w, h) to resize. (Default value = None) Returns: The loaded ...
Utility function to return the image net label for the final dense layer output index.
def lookup_imagenet_labels(indices): """Utility function to return the image net label for the final `dense` layer output index. Args: indices: Could be a single value or an array of indices whose labels should be looked up. Returns: Image net label corresponding to the image category. ...
Draws text over the image. Requires PIL.
def draw_text(img, text, position=(10, 10), font='FreeSans.ttf', font_size=14, color=(0, 0, 0)): """Draws text over the image. Requires PIL. Args: img: The image to use. text: The text string to overlay. position: The text (x, y) position. (Default value = (10, 10)) font: The tt...
Normalizes the numpy array to ( min_value max_value )
def normalize(array, min_value=0., max_value=1.): """Normalizes the numpy array to (min_value, max_value) Args: array: The numpy array min_value: The min value in normalized array (Default value = 0) max_value: The max value in normalized array (Default value = 1) Returns: ...
Determines the number of filters within the given layer.
def get_num_filters(layer): """Determines the number of filters within the given `layer`. Args: layer: The keras layer to use. Returns: Total number of filters within `layer`. For `keras.layers.Dense` layer, this is the total number of outputs. """ # Handle layers with no c...
Overlays array1 onto array2 with alpha blending.
def overlay(array1, array2, alpha=0.5): """Overlays `array1` onto `array2` with `alpha` blending. Args: array1: The first numpy array. array2: The second numpy array. alpha: The alpha value of `array1` as overlayed onto `array2`. This value needs to be between [0, 1], with 0...
All the logic for creating a new DataArray
def _infer_coords_and_dims(shape, coords, dims): """All the logic for creating a new DataArray""" if (coords is not None and not utils.is_dict_like(coords) and len(coords) != len(shape)): raise ValueError('coords is not dict-like, but it has %s items, ' 'which does ...
Convert a DataArray to a Dataset.
def to_dataset(self, dim=None, name=None): """Convert a DataArray to a Dataset. Parameters ---------- dim : str, optional Name of the dimension on this array along which to split this array into separate variables. If not provided, this array is converted ...
Return a mapping of all MultiIndex levels and their corresponding coordinate name.
def _level_coords(self): """Return a mapping of all MultiIndex levels and their corresponding coordinate name. """ level_coords = OrderedDict() for cname, var in self._coords.items(): if var.ndim == 1 and isinstance(var, IndexVariable): level_names = v...
Mapping of pandas. Index objects used for label based indexing
def indexes(self): """Mapping of pandas.Index objects used for label based indexing """ if self._indexes is None: self._indexes = default_indexes(self._coords, self.dims) return Indexes(self._indexes)
Given names of coordinates reset them to become variables.
def reset_coords(self, names=None, drop=False, inplace=None): """Given names of coordinates, reset them to become variables. Parameters ---------- names : str or list of str, optional Name(s) of non-index coordinates in this dataset to reset into variables. By de...
Manually trigger loading of this array s data from disk or a remote source into memory and return this array.
def load(self, **kwargs): """Manually trigger loading of this array's data from disk or a remote source into memory and return this array. Normally, it should not be necessary to call this method in user code, because all xarray functions should either work on deferred data or l...
Trigger computation in constituent dask arrays
def persist(self, **kwargs): """ Trigger computation in constituent dask arrays This keeps them as dask arrays but encourages them to keep data in memory. This is particularly useful when on a distributed machine. When on a single machine consider using ``.compute()`` instead. ...
Returns a copy of this array.
def copy(self, deep=True, data=None): """Returns a copy of this array. If `deep=True`, a deep copy is made of the data array. Otherwise, a shallow copy is made, so each variable in the new array's dataset is also a variable in this array's dataset. Use `data` to create a new ob...
Coerce this array s data into a dask arrays with the given chunks.
def chunk(self, chunks=None, name_prefix='xarray-', token=None, lock=False): """Coerce this array's data into a dask arrays with the given chunks. If this variable is a non-dask array, it will be converted to dask array. If it's a dask array, it will be rechunked to the given chun...
Return a new DataArray whose dataset is given by integer indexing along the specified dimension ( s ).
def isel(self, indexers=None, drop=False, **indexers_kwargs): """Return a new DataArray whose dataset is given by integer indexing along the specified dimension(s). See Also -------- Dataset.isel DataArray.sel """ indexers = either_dict_or_kwargs(indexers...
Return a new DataArray whose dataset is given by selecting index labels along the specified dimension ( s ).
def sel(self, indexers=None, method=None, tolerance=None, drop=False, **indexers_kwargs): """Return a new DataArray whose dataset is given by selecting index labels along the specified dimension(s). .. warning:: Do not try to assign values when using any of the indexing m...
Return a new DataArray whose dataset is given by pointwise integer indexing along the specified dimension ( s ).
def isel_points(self, dim='points', **indexers): """Return a new DataArray whose dataset is given by pointwise integer indexing along the specified dimension(s). See Also -------- Dataset.isel_points """ ds = self._to_temp_dataset().isel_points(dim=dim, **indexer...
Return a new DataArray whose dataset is given by pointwise selection of index labels along the specified dimension ( s ).
def sel_points(self, dim='points', method=None, tolerance=None, **indexers): """Return a new DataArray whose dataset is given by pointwise selection of index labels along the specified dimension(s). See Also -------- Dataset.sel_points """ ds =...
Conform this object onto a new set of indexes filling in missing values with NaN.
def reindex(self, indexers=None, method=None, tolerance=None, copy=True, **indexers_kwargs): """Conform this object onto a new set of indexes, filling in missing values with NaN. Parameters ---------- indexers : dict, optional Dictionary with keys giv...
Multidimensional interpolation of variables.
def interp(self, coords=None, method='linear', assume_sorted=False, kwargs={}, **coords_kwargs): """ Multidimensional interpolation of variables. coords : dict, optional Mapping from dimension names to the new coordinates. new coordinate can be an scalar, array-li...
Interpolate this object onto the coordinates of another object filling out of range values with NaN.
def interp_like(self, other, method='linear', assume_sorted=False, kwargs={}): """Interpolate this object onto the coordinates of another object, filling out of range values with NaN. Parameters ---------- other : Dataset or DataArray Object with ...
Returns a new DataArray with renamed coordinates or a new name.
def rename(self, new_name_or_name_dict=None, **names): """Returns a new DataArray with renamed coordinates or a new name. Parameters ---------- new_name_or_name_dict : str or dict-like, optional If the argument is dict-like, it it used as a mapping from old names...
Returns a new DataArray with swapped dimensions.
def swap_dims(self, dims_dict): """Returns a new DataArray with swapped dimensions. Parameters ---------- dims_dict : dict-like Dictionary whose keys are current dimension names and whose values are new names. Each value must already be a coordinate on this ...
Return a new object with an additional axis ( or axes ) inserted at the corresponding position in the array shape.
def expand_dims(self, dim=None, axis=None, **dim_kwargs): """Return a new object with an additional axis (or axes) inserted at the corresponding position in the array shape. If dim is already a scalar coordinate, it will be promoted to a 1D coordinate consisting of a single value. ...
Set DataArray ( multi - ) indexes using one or more existing coordinates.
def set_index(self, indexes=None, append=False, inplace=None, **indexes_kwargs): """Set DataArray (multi-)indexes using one or more existing coordinates. Parameters ---------- indexes : {dim: index, ...} Mapping from names matching dimensions and va...
Reset the specified index ( es ) or multi - index level ( s ).
def reset_index(self, dims_or_levels, drop=False, inplace=None): """Reset the specified index(es) or multi-index level(s). Parameters ---------- dims_or_levels : str or list Name(s) of the dimension(s) and/or multi-index level(s) that will be reset. drop ...
Rearrange index levels using input order.
def reorder_levels(self, dim_order=None, inplace=None, **dim_order_kwargs): """Rearrange index levels using input order. Parameters ---------- dim_order : optional Mapping from names matching dimensions and values given by lists representin...
Stack any number of existing dimensions into a single new dimension.
def stack(self, dimensions=None, **dimensions_kwargs): """ Stack any number of existing dimensions into a single new dimension. New dimensions will be added at the end, and the corresponding coordinate variables will be combined into a MultiIndex. Parameters ---------- ...
Unstack existing dimensions corresponding to MultiIndexes into multiple new dimensions.
def unstack(self, dim=None): """ Unstack existing dimensions corresponding to MultiIndexes into multiple new dimensions. New dimensions will be added at the end. Parameters ---------- dim : str or sequence of str, optional Dimension(s) over which to ...
Return a new DataArray object with transposed dimensions.
def transpose(self, *dims) -> 'DataArray': """Return a new DataArray object with transposed dimensions. Parameters ---------- *dims : str, optional By default, reverse the dimensions. Otherwise, reorder the dimensions to this order. Returns -----...
Drop coordinates or index labels from this DataArray.
def drop(self, labels, dim=None): """Drop coordinates or index labels from this DataArray. Parameters ---------- labels : scalar or list of scalars Name(s) of coordinate variables or index labels to drop. dim : str, optional Dimension along which to drop ...
Returns a new array with dropped labels for missing values along the provided dimension.
def dropna(self, dim, how='any', thresh=None): """Returns a new array with dropped labels for missing values along the provided dimension. Parameters ---------- dim : str Dimension along which to drop missing values. Dropping along multiple dimensions sim...
Fill missing values in this object.
def fillna(self, value): """Fill missing values in this object. This operation follows the normal broadcasting and alignment rules that xarray uses for binary arithmetic, except the result is aligned to this object (``join='left'``) instead of aligned to the intersection of inde...
Fill NaN values by propogating values forward
def ffill(self, dim, limit=None): '''Fill NaN values by propogating values forward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None ...
Fill NaN values by propogating values backward
def bfill(self, dim, limit=None): '''Fill NaN values by propogating values backward *Requires bottleneck.* Parameters ---------- dim : str Specifies the dimension along which to propagate values when filling. limit : int, default None ...
Reduce this array by applying func along some dimension ( s ).
def reduce(self, func, dim=None, axis=None, keep_attrs=None, **kwargs): """Reduce this array by applying `func` along some dimension(s). Parameters ---------- func : function Function which can be called in the form `f(x, axis=axis, **kwargs)` to return the resul...
Convert this array into a pandas object with the same shape.
def to_pandas(self): """Convert this array into a pandas object with the same shape. The type of the returned object depends on the number of DataArray dimensions: * 1D -> `pandas.Series` * 2D -> `pandas.DataFrame` * 3D -> `pandas.Panel` Only works for arrays w...
Convert this array and its coordinates into a tidy pandas. DataFrame.
def to_dataframe(self, name=None): """Convert this array and its coordinates into a tidy pandas.DataFrame. The DataFrame is indexed by the Cartesian product of index coordinates (in the form of a :py:class:`pandas.MultiIndex`). Other coordinates are included as columns in the DataFrame...
Convert this array into a pandas. Series.
def to_series(self): """Convert this array into a pandas.Series. The Series is indexed by the Cartesian product of index coordinates (in the form of a :py:class:`pandas.MultiIndex`). """ index = self.coords.to_index() return pd.Series(self.values.reshape(-1), index=index...