INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add a dataset and add it to the UI
def open(self, path): """Add a dataset and add it to the UI""" logger.debug("open dataset: %r", path) if path.startswith("http") or path.startswith("ws"): dataset = vaex.open(path, thread_mover=self.call_in_main_thread) else: dataset = vaex.open(path) self...
basic support for evaluate at server at least to run some unittest do not expect this to work from strings
def evaluate(self, expression, i1=None, i2=None, out=None, selection=None, delay=False): expression = _ensure_strings_from_expressions(expression) """basic support for evaluate at server, at least to run some unittest, do not expect this to work from strings""" result = self.server._call_dataset...
Decorator to transparantly accept delayed computation.
def delayed(f): '''Decorator to transparantly accept delayed computation. Example: >>> delayed_sum = ds.sum(ds.E, binby=ds.x, limits=limits, >>> shape=4, delay=True) >>> @vaex.delayed >>> def total_sum(sums): >>> return sums.sum() >>> sum_of_sums = total_sum(delay...
Find all columns that this selection depends on for df ds
def _depending_columns(self, ds): '''Find all columns that this selection depends on for df ds''' depending = set() for expression in self.expressions: expression = ds._expr(expression) # make sure it is an expression depending |= expression.variables() if self.p...
TODO: doc + server side implementation
def limits(self, value, square=False): """TODO: doc + server side implementation""" if isinstance(value, six.string_types): import re match = re.match(r"(\d*)(\D*)", value) if match is None: raise ValueError("do not understand limit specifier %r, examp...
Plot the subspace using sane defaults to get a quick look at the data.
def plot(self, grid=None, size=256, limits=None, square=False, center=None, weight=None, weight_stat="mean", figsize=None, aspect="auto", f="identity", axes=None, xlabel=None, ylabel=None, group_by=None, group_limits=None, group_colors='jet', group_labels=None, group_count=None, v...
Plot the subspace using sane defaults to get a quick look at the data.
def plot1d(self, grid=None, size=64, limits=None, weight=None, figsize=None, f="identity", axes=None, xlabel=None, ylabel=None, **kwargs): """Plot the subspace using sane defaults to get a quick look at the data. :param grid: A 2d numpy array with the counts, if None it will be calculated using limits ...
Returns a bounded subspace ( SubspaceBounded ) with limits given by Subspace. limits_sigma ()
def bounded_by_sigmas(self, sigmas=3, square=False): """Returns a bounded subspace (SubspaceBounded) with limits given by Subspace.limits_sigma() :rtype: SubspaceBounded """ bounds = self.limits_sigma(sigmas=sigmas, square=square) return SubspaceBounded(self, bounds)
Helper function for returning tasks results result when immediate is True otherwise the task itself which is a promise
def _task(self, task, progressbar=False): """Helper function for returning tasks results, result when immediate is True, otherwise the task itself, which is a promise""" if self.delay: # should return a task or a promise nesting it return self.executor.schedule(task) else...
Sort table by given column number.
def sort(self, Ncol, order): """Sort table by given column number. """ self.emit(QtCore.SIGNAL("layoutAboutToBeChanged()")) if Ncol == 0: print("by name") # get indices, sorted by pair name sortlist = list(zip(self.pairs, list(range(len(self.pairs)))))...
: param DatasetLocal dataset: dataset to export: param str path: path for file: param lis [ str ] column_names: list of column names to export or None for all columns: param str byteorder: = for native < for little endian and > for big endian: param bool shuffle: export rows in random order: param bool selection: expor...
def export_hdf5_v1(dataset, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all columns :pa...
Read header data from Gadget data file filename with Gadget file type gtype. Returns offsets of positions and velocities.
def getinfo(filename, seek=None): """Read header data from Gadget data file 'filename' with Gadget file type 'gtype'. Returns offsets of positions and velocities.""" DESC = '=I4sII' # struct formatting string HEAD = '=I6I6dddii6iiiddddii6ii60xI' # struct formatting string keys...
: param DatasetLocal dataset: dataset to export: param str path: path for file: param lis [ str ] column_names: list of column names to export or None for all columns: param str byteorder: = for native < for little endian and > for big endian: param bool shuffle: export rows in random order: param bool selection: expor...
def _export(dataset_input, dataset_output, random_index_column, path, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names:...
: param DatasetLocal dataset: dataset to export: param str path: path for file: param lis [ str ] column_names: list of column names to export or None for all columns: param bool shuffle: export rows in random order: param bool selection: export selection or not: param progress: progress callback that gets a progress f...
def export_fits(dataset, path, column_names=None, shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for all column...
clear the cursor
def clear(self, event): """clear the cursor""" if self.useblit: self.background = ( self.canvas.copy_from_bbox(self.canvas.figure.bbox)) for line in self.vlines + self.hlines: line.set_visible(False) self.ellipse.set_visible(False)
Used for unittesting to make sure the plots are all done
def _wait(self): """Used for unittesting to make sure the plots are all done""" logger.debug("will wait for last plot to finish") self._plot_event = threading.Event() self.queue_update._wait() self.queue_replot._wait() self.queue_redraw._wait() qt_app = QtCore.QCo...
Each layer has it s own ranges_grid computed now unless something went wrong But all layers are shown with the same ranges ( self. state. ranges_viewport ) If any of the ranges is None take the min/ max of each layer
def _update_step2(self, layers): """Each layer has it's own ranges_grid computed now, unless something went wrong But all layers are shown with the same ranges (self.state.ranges_viewport) If any of the ranges is None, take the min/max of each layer """ logger.info("done with ran...
Generates a list with start end stop indices of length parts [ ( 0 length/ parts )... (.. length ) ]
def subdivide(length, parts=None, max_length=None): """Generates a list with start end stop indices of length parts, [(0, length/parts), ..., (.., length)]""" if max_length: i1 = 0 done = False while not done: i2 = min(length, i1 + max_length) # print i1, i2 ...
Open document by the default handler of the OS could be a url opened by a browser a text file by an editor etc
def os_open(document): """Open document by the default handler of the OS, could be a url opened by a browser, a text file by an editor etc""" osname = platform.system().lower() if osname == "darwin": os.system("open \"" + document + "\"") if osname == "linux": cmd = "xdg-open \"" + docum...
Flexible writing where f can be a filename or f object if filename closed after writing
def write_to(f, mode): """Flexible writing, where f can be a filename or f object, if filename, closed after writing""" if hasattr(f, 'write'): yield f else: f = open(f, mode) yield f f.close()
Combines all masks from a list of arrays and logically ors them into a single mask
def _split_and_combine_mask(arrays): '''Combines all masks from a list of arrays, and logically ors them into a single mask''' masks = [np.ma.getmaskarray(block) for block in arrays if np.ma.isMaskedArray(block)] arrays = [block.data if np.ma.isMaskedArray(block) else block for block in arrays] mask = None if mask...
Plot conting contours on 2D grid.
def plot2d_contour(self, x=None, y=None, what="count(*)", limits=None, shape=256, selection=None, f="identity", figsize=None, xlabel=None, ylabel=None, aspect="auto", levels=None, fill=False, colorbar=False, colorbar_label=None, ...
: param DatasetLocal dataset: dataset to export: param str path: path for file: param lis [ str ] column_names: list of column names to export or None for all columns: param str byteorder: = for native < for little endian and > for big endian: param bool shuffle: export rows in random order: param bool selection: expor...
def _export_table(dataset, column_names=None, byteorder="=", shuffle=False, selection=False, progress=None, virtual=True, sort=None, ascending=True): """ :param DatasetLocal dataset: dataset to export :param str path: path for file :param lis[str] column_names: list of column names to export or None for...
Evaluates expression and drop the result usefull for benchmarking since vaex is usually lazy
def nop(self, expression, progress=False, delay=False): """Evaluates expression, and drop the result, usefull for benchmarking, since vaex is usually lazy""" expression = _ensure_string_from_expression(expression) def map(ar): pass def reduce(a, b): pass r...
Estimate the mutual information between and x and y on a grid with shape mi_shape and mi_limits possibly on a grid defined by binby.
def mutual_information(self, x, y=None, mi_limits=None, mi_shape=256, binby=[], limits=None, shape=default_shape, sort=False, selection=False, delay=False): """Estimate the mutual information between and x and y on a grid with shape mi_shape and mi_limits, possibly on a grid defined by binby. If sort i...
Count the number of non - NaN values ( or all if expression is None or * ).
def count(self, expression=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None): """Count the number of non-NaN values (or all, if expression is None or "*"). Example: >>> df.count() 330000 >>> df.count("*") 330000....
Return the first element of a binned expression where the values each bin are sorted by order_expression.
def first(self, expression, order_expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, edges=False, progress=None): """Return the first element of a binned `expression`, where the values each bin are sorted by `order_expression`. Example: >>> import vaex ...
Calculate the mean for expression possibly on a grid defined by binby.
def mean(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False): """Calculate the mean for expression, possibly on a grid defined by binby. Example: >>> df.mean("x") -0.067131491264005971 >>> df.mean("(x**2+y**2)*...
Calculate the sum for the given expression possible on a grid defined by binby
def sum(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False): """Calculate the sum for the given expression, possible on a grid defined by binby Example: >>> df.sum("L") 304054882.49378014 >>> df.sum("L", binby=...
Calculate the standard deviation for the given expression possible on a grid defined by binby
def std(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the standard deviation for the given expression, possible on a grid defined by binby >>> df.std("vz") 110.31773397535071 >>> df.std("vz", binby=["(x**2+y**2)...
Calculate the covariance cov [ x y ] between and x and y possibly on a grid defined by binby.
def covar(self, x, y, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the covariance cov[x,y] between and x and y, possibly on a grid defined by binby. Example: >>> df.covar("x**2+y**2+z**2", "-log(-E+1)") array(52.69461456005138) ...
Calculate the correlation coefficient cov [ x y ]/ ( std [ x ] * std [ y ] ) between and x and y possibly on a grid defined by binby.
def correlation(self, x, y=None, binby=[], limits=None, shape=default_shape, sort=False, sort_key=np.abs, selection=False, delay=False, progress=None): """Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between and x and y, possibly on a grid defined by binby. Example: >>> df.co...
Calculate the covariance matrix for x and y or more expressions possibly on a grid defined by binby.
def cov(self, x, y=None, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the covariance matrix for x and y or more expressions, possibly on a grid defined by binby. Either x and y are expressions, e.g: >>> df.cov("x", "y") Or only...
Calculate the minimum and maximum for expressions possibly on a grid defined by binby.
def minmax(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): """Calculate the minimum and maximum for expressions, possibly on a grid defined by binby. Example: >>> df.minmax("x") array([-128.293991, 271.365997]) >>> d...
Calculate the minimum for given expressions possibly on a grid defined by binby.
def min(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False): """Calculate the minimum for given expressions, possibly on a grid defined by binby. Example: >>> df.min("x") array(-128.293991) >>> df.min(["x", "y...
Calculate the median possibly on a grid defined by binby.
def median_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=256, percentile_limits="minmax", selection=False, delay=False): """Calculate the median , possibly on a grid defined by binby. NOTE: this value is approximated by calculating the cumulative ...
Calculate the percentile given by percentage possibly on a grid defined by binby.
def percentile_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=1024, percentile_limits="minmax", selection=False, delay=False): """Calculate the percentile given by percentage, possibly on a grid defined by binby. NOTE: this value is approximated by...
Calculate the [ min max ] range for expression containing approximately a percentage of the data as defined by percentage.
def limits_percentage(self, expression, percentage=99.73, square=False, delay=False): """Calculate the [min, max] range for expression, containing approximately a percentage of the data as defined by percentage. The range is symmetric around the median, i.e., for a percentage of 90, this gives ...
Calculate the [ min max ] range for expression as described by value which is 99. 7% by default.
def limits(self, expression, value=None, square=False, selection=None, delay=False, shape=None): """Calculate the [min, max] range for expression, as described by value, which is '99.7%' by default. If value is a list of the form [minvalue, maxvalue], it is simply returned, this is for convenience when...
Calculate/ estimate the mode.
def mode(self, expression, binby=[], limits=None, shape=256, mode_shape=64, mode_limits=None, progressbar=False, selection=None): """Calculate/estimate the mode.""" if len(binby) == 0: raise ValueError("only supported with binby argument given") else: # todo, fix progress...
Viz 1d 2d or 3d in a Jupyter notebook
def plot_widget(self, x, y, z=None, grid=None, shape=256, limits=None, what="count(*)", figsize=None, f="identity", figure_key=None, fig=None, axes=None, xlabel=None, ylabel=None, title=None, show=True, selection=[None, True], colormap="afmhot", grid_limits=None, normalize="norma...
Count non missing value for expression on an array which represents healpix data.
def healpix_count(self, expression=None, healpix_expression=None, healpix_max_level=12, healpix_level=8, binby=None, limits=None, shape=default_shape, delay=False, progress=None, selection=None): """Count non missing value for expression on an array which represents healpix data. :param expression: Exp...
Viz data in 2d using a healpix column.
def healpix_plot(self, healpix_expression="source_id/34359738368", healpix_max_level=12, healpix_level=8, what="count(*)", selection=None, grid=None, healpix_input="equatorial", healpix_output="galactic", f=None, colormap="afmhot", grid_limits=None, image_s...
Use at own risk requires ipyvolume
def plot3d(self, x, y, z, vx=None, vy=None, vz=None, vwhat=None, limits=None, grid=None, what="count(*)", shape=128, selection=[None, True], f=None, vcount_limits=None, smooth_pre=None, smooth_post=None, grid_limits=None, normalize="normalize", colormap="afmhot", figure_key=...
Gives direct access to the columns only ( useful for tab completion ).
def col(self): """Gives direct access to the columns only (useful for tab completion). Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion. Columns can be accesed by there names, which are attributes. The attribues are currently expression...
Return the size in bytes the whole DataFrame requires ( or the selection ) respecting the active_fraction.
def byte_size(self, selection=False, virtual=False): """Return the size in bytes the whole DataFrame requires (or the selection), respecting the active_fraction.""" bytes_per_row = 0 N = self.count(selection=selection) extra = 0 for column in list(self.get_column_names(virtual=vi...
Return the numpy dtype for the given expression if not a column the first row will be evaluated to get the dtype.
def dtype(self, expression, internal=False): """Return the numpy dtype for the given expression, if not a column, the first row will be evaluated to get the dtype.""" expression = _ensure_string_from_expression(expression) if expression in self.variables: return np.float64(1).dtype ...
Gives a Pandas series object containing all numpy dtypes of all columns ( except hidden ).
def dtypes(self): """Gives a Pandas series object containing all numpy dtypes of all columns (except hidden).""" from pandas import Series return Series({column_name:self.dtype(column_name) for column_name in self.get_column_names()})
Return if a column is a masked ( numpy. ma ) column.
def is_masked(self, column): '''Return if a column is a masked (numpy.ma) column.''' column = _ensure_string_from_expression(column) if column in self.columns: return np.ma.isMaskedArray(self.columns[column]) return False
Returns the unit ( an astropy. unit. Units object ) for the expression.
def unit(self, expression, default=None): """Returns the unit (an astropy.unit.Units object) for the expression. Example >>> import vaex >>> ds = vaex.example() >>> df.unit("x") Unit("kpc") >>> df.unit("x*L") Unit("km kpc2 / s") :param expressi...
Find a set of columns ( names ) which have the ucd or part of the ucd.
def ucd_find(self, ucds, exclude=[]): """Find a set of columns (names) which have the ucd, or part of the ucd. Prefixed with a ^, it will only match the first part of the ucd. Example >>> df.ucd_find('pos.eq.ra', 'pos.eq.dec') ['RA', 'DEC'] >>> df.ucd_find('pos.eq.ra',...
Each DataFrame has a directory where files are stored for metadata etc.
def get_private_dir(self, create=False): """Each DataFrame has a directory where files are stored for metadata etc. Example >>> import vaex >>> ds = vaex.example() >>> vaex.get_private_dir() '/Users/users/breddels/.vaex/dfs/_Users_users_breddels_vaex-testing_data_helmi-...
Return the internal state of the DataFrame in a dictionary
def state_get(self): """Return the internal state of the DataFrame in a dictionary Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>> df.state_get() {'active_range': [0, 1], 'column_names': ['x', 'y',...
Sets the internal state of the df
def state_set(self, state, use_active_range=False): """Sets the internal state of the df Example: >>> import vaex >>> df = vaex.from_scalars(x=1, y=2) >>> df # x y r 0 1 2 2.23607 >>> df['r'] = (df.x**2 + df.y**2)**0.5 >>>...
Load a state previously stored by: meth: DataFrame. state_store see also: meth: DataFrame. state_set.
def state_load(self, f, use_active_range=False): """Load a state previously stored by :meth:`DataFrame.state_store`, see also :meth:`DataFrame.state_set`.""" state = vaex.utils.read_json_or_yaml(f) self.state_set(state, use_active_range=use_active_range)
Removes the file with the virtual column etc it does not change the current virtual columns etc.
def remove_virtual_meta(self): """Removes the file with the virtual column etc, it does not change the current virtual columns etc.""" dir = self.get_private_dir(create=True) path = os.path.join(dir, "virtual_meta.yaml") try: if os.path.exists(path): os.remove...
Writes virtual columns variables and their ucd description and units.
def write_virtual_meta(self): """Writes virtual columns, variables and their ucd,description and units. The default implementation is to write this to a file called virtual_meta.yaml in the directory defined by :func:`DataFrame.get_private_dir`. Other implementation may store this in the DataFr...
Will read back the virtual column etc written by: func: DataFrame. write_virtual_meta. This will be done when opening a DataFrame.
def update_virtual_meta(self): """Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame.""" import astropy.units try: path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml") ...
Writes all meta data ucd description and units
def write_meta(self): """Writes all meta data, ucd,description and units The default implementation is to write this to a file called meta.yaml in the directory defined by :func:`DataFrame.get_private_dir`. Other implementation may store this in the DataFrame file itself. (For instance ...
Generate a Subspaces object based on a custom list of expressions or all possible combinations based on dimension
def subspaces(self, expressions_list=None, dimensions=None, exclude=None, **kwargs): """Generate a Subspaces object, based on a custom list of expressions or all possible combinations based on dimension :param expressions_list: list of list of expressions, where the inner list defines the subsp...
Set the variable to an expression or value defined by expression_or_value.
def set_variable(self, name, expression_or_value, write=True): """Set the variable to an expression or value defined by expression_or_value. Example >>> df.set_variable("a", 2.) >>> df.set_variable("b", "a**2") >>> df.get_variable("b") 'a**2' >>> df.evaluate_var...
Evaluates the variable given by name.
def evaluate_variable(self, name): """Evaluates the variable given by name.""" if isinstance(self.variables[name], six.string_types): # TODO: this does not allow more than one level deep variable, like a depends on b, b on c, c is a const value = eval(self.variables[name], expres...
Internal use ignores the filter
def _evaluate_selection_mask(self, name="default", i1=None, i2=None, selection=None, cache=False): """Internal use, ignores the filter""" i1 = i1 or 0 i2 = i2 or len(self) scope = scopes._BlockScopeSelection(self, i1, i2, selection, cache=cache) return scope.evaluate(name)
Return a list of [ ( column_name ndarray )... ) ] pairs where the ndarray corresponds to the evaluated data
def to_items(self, column_names=None, selection=None, strings=True, virtual=False): """Return a list of [(column_name, ndarray), ...)] pairs where the ndarray corresponds to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, vi...
Return a dict containing the ndarray corresponding to the evaluated data
def to_dict(self, column_names=None, selection=None, strings=True, virtual=False): """Return a dict containing the ndarray corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtual) is used :pa...
Return a copy of the DataFrame if selection is None it does not copy the data it just has a reference
def to_copy(self, column_names=None, selection=None, strings=True, virtual=False, selections=True): """Return a copy of the DataFrame, if selection is None, it does not copy the data, it just has a reference :param column_names: list of column names, to copy, when None DataFrame.get_column_names(string...
Return a pandas DataFrame containing the ndarray corresponding to the evaluated data
def to_pandas_df(self, column_names=None, selection=None, strings=True, virtual=False, index_name=None): """Return a pandas DataFrame containing the ndarray corresponding to the evaluated data If index is given, that column is used for the index of the dataframe. Example >>> df_pan...
Returns an arrow Table object containing the arrays corresponding to the evaluated data
def to_arrow_table(self, column_names=None, selection=None, strings=True, virtual=False): """Returns an arrow Table object containing the arrays corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=strings, virtual=virtua...
Returns a astropy table object containing the ndarrays corresponding to the evaluated data
def to_astropy_table(self, column_names=None, selection=None, strings=True, virtual=False, index=None): """Returns a astropy table object containing the ndarrays corresponding to the evaluated data :param column_names: list of column names, to export, when None DataFrame.get_column_names(strings=string...
Validate an expression ( may throw Exceptions )
def validate_expression(self, expression): """Validate an expression (may throw Exceptions)""" # return self.evaluate(expression, 0, 2) vars = set(self.get_column_names()) | set(self.variables.keys()) funcs = set(expression_namespace.keys()) return vaex.expresso.validate_expressi...
Add an in memory array as a column.
def add_column(self, name, f_or_array): """Add an in memory array as a column.""" if isinstance(f_or_array, (np.ndarray, Column)): data = ar = f_or_array # it can be None when we have an 'empty' DataFrameArrays if self._length_original is None: self._l...
Renames a column not this is only the in memory name this will not be reflected on disk
def rename_column(self, name, new_name, unique=False, store_in_state=True): """Renames a column, not this is only the in memory name, this will not be reflected on disk""" new_name = vaex.utils.find_valid_name(new_name, used=[] if not unique else list(self)) data = self.columns.get(name) ...
Add a healpix ( in memory ) column based on a longitude and latitude
def add_column_healpix(self, name="healpix", longitude="ra", latitude="dec", degrees=True, healpix_order=12, nest=True): """Add a healpix (in memory) column based on a longitude and latitude :param name: Name of column :param longitude: longitude expression :param latitude: latitude exp...
Propagates uncertainties ( full covariance matrix ) for a set of virtual columns.
def propagate_uncertainties(self, columns, depending_variables=None, cov_matrix='auto', covariance_format="{}_{}_covariance", uncertainty_format="{}_uncertainty"): """Propagates uncertainties (full covariance matrix) for a set of virtual columns. ...
Convert cartesian to polar coordinates
def add_virtual_columns_cartesian_to_polar(self, x="x", y="y", radius_out="r_polar", azimuth_out="phi_polar", propagate_uncertainties=False, radians=False): """Convert cartesian to polar coordinates :param x: ...
Concert velocities from a cartesian to a spherical coordinate system
def add_virtual_columns_cartesian_velocities_to_spherical(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", vlong="vlong", vlat="vlat", distance=None): """Concert velocities from a cartesian to a spherical coordinate system TODO: errors :param x: name of x column (input) :...
Convert cartesian to polar velocities.
def add_virtual_columns_cartesian_velocities_to_polar(self, x="x", y="y", vx="vx", radius_polar=None, vy="vy", vr_out="vr_polar", vazimuth_out="vphi_polar", propagate_uncertainties=False,): """Convert cartesian to polar velocities. :param x: ...
Convert cylindrical polar velocities to Cartesian.
def add_virtual_columns_polar_velocities_to_cartesian(self, x='x', y='y', azimuth=None, vr='vr_polar', vazimuth='vphi_polar', vx_out='vx', vy_out='vy', propagate_uncertainties=False): """ Convert cylindrical polar velocities to Cartesian. :param x: :param y: :param azimuth: Optional exp...
Rotation in 2d.
def add_virtual_columns_rotation(self, x, y, xnew, ynew, angle_degrees, propagate_uncertainties=False): """Rotation in 2d. :param str x: Name/expression of x column :param str y: idem for y :param str xnew: name of transformed x column :param str ynew: :param float angle...
Convert spherical to cartesian coordinates.
def add_virtual_columns_spherical_to_cartesian(self, alpha, delta, distance, xname="x", yname="y", zname="z", propagate_uncertainties=False, center=[0, 0, 0], center_name="solar_position", radians=False): """Co...
Convert cartesian to spherical coordinates.
def add_virtual_columns_cartesian_to_spherical(self, x="x", y="y", z="z", alpha="l", delta="b", distance="distance", radians=False, center=None, center_name="solar_position"): """Convert cartesian to spherical coordinates. :param x: :param y: :param z: :param alpha: :p...
Add aitoff ( https:// en. wikipedia. org/ wiki/ Aitoff_projection ) projection
def add_virtual_columns_aitoff(self, alpha, delta, x, y, radians=True): """Add aitoff (https://en.wikipedia.org/wiki/Aitoff_projection) projection :param alpha: azimuth angle :param delta: polar angle :param x: output name for x coordinate :param y: output name for y coordinate ...
Add a virtual column to the DataFrame.
def add_virtual_column(self, name, expression, unique=False): """Add a virtual column to the DataFrame. Example: >>> df.add_virtual_column("r", "sqrt(x**2 + y**2 + z**2)") >>> df.select("r < 10") :param: str name: name of virtual column :param: expression: expression f...
Deletes a virtual column from a DataFrame.
def delete_virtual_column(self, name): """Deletes a virtual column from a DataFrame.""" del self.virtual_columns[name] self.signal_column_changed.emit(self, name, "delete")
Add a variable to to a DataFrame.
def add_variable(self, name, expression, overwrite=True, unique=True): """Add a variable to to a DataFrame. A variable may refer to other variables, and virtual columns and expression may refer to variables. Example >>> df.add_variable('center', 0) >>> df.add_virtual_column('x...
Deletes a variable from a DataFrame.
def delete_variable(self, name): """Deletes a variable from a DataFrame.""" del self.variables[name] self.signal_variable_changed.emit(self, name, "delete")
Return a shallow copy a DataFrame with the last n rows.
def tail(self, n=10): """Return a shallow copy a DataFrame with the last n rows.""" N = len(self) # self.cat(i1=max(0, N-n), i2=min(len(self), N)) return self[max(0, N - n):min(len(self), N)]
Display the first and last n elements of a DataFrame.
def head_and_tail_print(self, n=5): """Display the first and last n elements of a DataFrame.""" from IPython import display display.display(display.HTML(self._head_and_tail_table(n)))
Give a description of the DataFrame.
def describe(self, strings=True, virtual=True, selection=None): """Give a description of the DataFrame. >>> import vaex >>> df = vaex.example()[['x', 'y', 'z']] >>> df.describe() x y z dtype float64 float64 float64 co...
Display the DataFrame from row i1 till i2
def cat(self, i1, i2, format='html'): """Display the DataFrame from row i1 till i2 For format, see https://pypi.org/project/tabulate/ :param int i1: Start row :param int i2: End row. :param str format: Format to use, e.g. 'html', 'plain', 'latex' """ from IPytho...
Set the current row and emit the signal signal_pick.
def set_current_row(self, value): """Set the current row, and emit the signal signal_pick.""" if (value is not None) and ((value < 0) or (value >= len(self))): raise IndexError("index %d out of range [0,%d]" % (value, len(self))) self._current_row = value self.signal_pick.emi...
Return a list of column names
def get_column_names(self, virtual=True, strings=True, hidden=False, regex=None): """Return a list of column names Example: >>> import vaex >>> df = vaex.from_scalars(x=1, x2=2, y=3, s='string') >>> df['r'] = (df.x**2 + df.y**2)**2 >>> df.get_column_names() ['x'...
Sets the active_fraction set picked row to None and remove selection.
def set_active_fraction(self, value): """Sets the active_fraction, set picked row to None, and remove selection. TODO: we may be able to keep the selection, if we keep the expression, and also the picked row """ if value != self._active_fraction: self._active_fraction = valu...
Sets the active_fraction set picked row to None and remove selection.
def set_active_range(self, i1, i2): """Sets the active_fraction, set picked row to None, and remove selection. TODO: we may be able to keep the selection, if we keep the expression, and also the picked row """ logger.debug("set active range to: %r", (i1, i2)) self._active_fracti...
Return a DataFrame where all columns are trimmed by the active range.
def trim(self, inplace=False): '''Return a DataFrame, where all columns are 'trimmed' by the active range. For the returned DataFrame, df.get_active_range() returns (0, df.length_original()). {note_copy} :param inplace: {inplace} :rtype: DataFrame ''' df = self...
Returns a DataFrame containing only rows indexed by indices
def take(self, indices): '''Returns a DataFrame containing only rows indexed by indices {note_copy} Example: >>> import vaex, numpy as np >>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd']), x=np.arange(1,5)) >>> df.take([0,2]) # s x 0 a...
Return a DataFrame containing only the filtered rows.
def extract(self): '''Return a DataFrame containing only the filtered rows. {note_copy} The resulting DataFrame may be more efficient to work with when the original DataFrame is heavily filtered (contains just a small number of rows). If no filtering is applied, it returns a t...
Returns a DataFrame with a random set of rows
def sample(self, n=None, frac=None, replace=False, weights=None, random_state=None): '''Returns a DataFrame with a random set of rows {note_copy} Provide either n or frac. Example: >>> import vaex, numpy as np >>> df = vaex.from_arrays(s=np.array(['a', 'b', 'c', 'd'])...
Returns a list containing random portions of the DataFrame.
def split_random(self, frac, random_state=None): '''Returns a list containing random portions of the DataFrame. {note_copy} Example: >>> import vaex, import numpy as np >>> np.random.seed(111) >>> df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> fo...
Returns a list containing ordered subsets of the DataFrame.
def split(self, frac): '''Returns a list containing ordered subsets of the DataFrame. {note_copy} Example: >>> import vaex >>> df = vaex.from_arrays(x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> for dfs in df.split(frac=0.3): ... print(dfs.x.values) ... ...