INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Checks element - wise that this is less than or equal to other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the le over. level: The Multilevel index level to apply le over. Returns: A new DataFrame filled with Booleans.
def le(self, other, axis="columns", level=None): """Checks element-wise that this is less than or equal to other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the le over. level: The Multilevel index level to apply le ov...
Checks element - wise that this is less than other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the lt over. level: The Multilevel index level to apply lt over. Returns: A new DataFrame filled with Booleans.
def lt(self, other, axis="columns", level=None): """Checks element-wise that this is less than other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the lt over. level: The Multilevel index level to apply lt over. ...
Computes mean across the DataFrame. Args: axis ( int ): The axis to take the mean on. skipna ( bool ): True to skip NA values false otherwise. Returns: The mean of the DataFrame. ( Pandas series )
def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): """Computes mean across the DataFrame. Args: axis (int): The axis to take the mean on. skipna (bool): True to skip NA values, false otherwise. Returns: The mean of the D...
Computes median across the DataFrame. Args: axis ( int ): The axis to take the median on. skipna ( bool ): True to skip NA values false otherwise. Returns: The median of the DataFrame. ( Pandas series )
def median(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): """Computes median across the DataFrame. Args: axis (int): The axis to take the median on. skipna (bool): True to skip NA values, false otherwise. Returns: The median ...
Returns the memory usage of each column in bytes Args: index ( bool ): Whether to include the memory usage of the DataFrame s index in returned Series. Defaults to True deep ( bool ): If True introspect the data deeply by interrogating objects dtypes for system - level memory consumption. Defaults to False Returns: A S...
def memory_usage(self, index=True, deep=False): """Returns the memory usage of each column in bytes Args: index (bool): Whether to include the memory usage of the DataFrame's index in returned Series. Defaults to True deep (bool): If True, introspect the da...
Perform min across the DataFrame. Args: axis ( int ): The axis to take the min on. skipna ( bool ): True to skip NA values false otherwise. Returns: The min of the DataFrame.
def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): """Perform min across the DataFrame. Args: axis (int): The axis to take the min on. skipna (bool): True to skip NA values, false otherwise. Returns: The min of the DataFr...
Mods this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the mod against this. axis: The axis to mod over. level: The Multilevel index level to apply mod over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Mod applied.
def mod(self, other, axis="columns", level=None, fill_value=None): """Mods this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the mod against this. axis: The axis to mod over. level: The Multilevel index level to app...
Perform mode across the DataFrame. Args: axis ( int ): The axis to take the mode on. numeric_only ( bool ): if True only apply to numeric columns. Returns: DataFrame: The mode of the DataFrame.
def mode(self, axis=0, numeric_only=False, dropna=True): """Perform mode across the DataFrame. Args: axis (int): The axis to take the mode on. numeric_only (bool): if True, only apply to numeric columns. Returns: DataFrame: The mode of the DataFrame....
Multiplies this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the multiply against this. axis: The axis to multiply over. level: The Multilevel index level to apply multiply over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Multiply applied.
def mul(self, other, axis="columns", level=None, fill_value=None): """Multiplies this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the multiply against this. axis: The axis to multiply over. level: The Multilevel in...
Checks element - wise that this is not equal to other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the ne over. level: The Multilevel index level to apply ne over. Returns: A new DataFrame filled with Booleans.
def ne(self, other, axis="columns", level=None): """Checks element-wise that this is not equal to other. Args: other: A DataFrame or Series or scalar to compare to. axis: The axis to perform the ne over. level: The Multilevel index level to apply ne over. ...
Return Series with number of distinct observations over requested axis. Args: axis: { 0 or index 1 or columns } default 0 dropna: boolean default True Returns: nunique: Series
def nunique(self, axis=0, dropna=True): """Return Series with number of distinct observations over requested axis. Args: axis : {0 or 'index', 1 or 'columns'}, default 0 dropna : boolean, default True Returns: nunique : Series ""...
Pow this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to apply pow over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Pow applied.
def pow(self, other, axis="columns", level=None, fill_value=None): """Pow this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to appl...
Return the product of the values for the requested axis Args: axis: { index ( 0 ) columns ( 1 ) } skipna: boolean default True level: int or level name default None numeric_only: boolean default None min_count: int default 0 Returns: prod: Series or DataFrame ( if level specified )
def prod( self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs ): """Return the product of the values for the requested axis Args: axis : {index (0), columns (1)} skipna : bool...
Return values at the given quantile over requested axis a la numpy. percentile. Args: q ( float ): 0 < = q < = 1 the quantile ( s ) to compute axis ( int ): 0 or index for row - wise 1 or columns for column - wise interpolation: { linear lower higher midpoint nearest } Specifies which interpolation method to use Return...
def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"): """Return values at the given quantile over requested axis, a la numpy.percentile. Args: q (float): 0 <= q <= 1, the quantile(s) to compute axis (int): 0 or 'index' for row-wise, ...
Compute numerical data ranks ( 1 through n ) along axis. Equal values are assigned a rank that is the [ method ] of the ranks of those values. Args: axis ( int ): 0 or index for row - wise 1 or columns for column - wise method: { average min max first dense } Specifies which method to use for equal vals numeric_only ( ...
def rank( self, axis=0, method="average", numeric_only=None, na_option="keep", ascending=True, pct=False, ): """ Compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the [method] of ...
Reset this index to default and create column from current index. Args: level: Only remove the given levels from the index. Removes all levels by default drop: Do not try to insert index into DataFrame columns. This resets the index to the default integer index. inplace: Modify the DataFrame in place ( do not create a ...
def reset_index( self, level=None, drop=False, inplace=False, col_level=0, col_fill="" ): """Reset this index to default and create column from current index. Args: level: Only remove the given levels from the index. Removes all levels by default ...
Mod this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the div against this. axis: The axis to div over. level: The Multilevel index level to apply div over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the rdiv applied.
def rmod(self, other, axis="columns", level=None, fill_value=None): """Mod this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the div against this. axis: The axis to div over. level: The Multilevel index level to app...
Round each element in the DataFrame. Args: decimals: The number of decimals to round to. Returns: A new DataFrame.
def round(self, decimals=0, *args, **kwargs): """Round each element in the DataFrame. Args: decimals: The number of decimals to round to. Returns: A new DataFrame. """ return self.__constructor__( query_compiler=self._query_compile...
Pow this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to apply pow over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Pow applied.
def rpow(self, other, axis="columns", level=None, fill_value=None): """Pow this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the pow against this. axis: The axis to pow over. level: The Multilevel index level to app...
Subtract a DataFrame/ Series/ scalar from this DataFrame. Args: other: The object to use to apply the subtraction to this. axis: The axis to apply the subtraction over. level: Mutlilevel index level to subtract over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the subtraciont applied.
def rsub(self, other, axis="columns", level=None, fill_value=None): """Subtract a DataFrame/Series/scalar from this DataFrame. Args: other: The object to use to apply the subtraction to this. axis: The axis to apply the subtraction over. level: Mutlilevel index...
Div this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the div against this. axis: The axis to div over. level: The Multilevel index level to apply div over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the rdiv applied.
def rtruediv(self, other, axis="columns", level=None, fill_value=None): """Div this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the div against this. axis: The axis to div over. level: The Multilevel index level to...
Returns a random sample of items from an axis of object. Args: n: Number of items from axis to return. Cannot be used with frac. Default = 1 if frac = None. frac: Fraction of axis items to return. Cannot be used with n. replace: Sample with or without replacement. Default = False. weights: Default None results in equal...
def sample( self, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ): """Returns a random sample of items from an axis of object. Args: n: Number of items from axis to return. Cannot be used...
Assign desired index to given axis. Args: labels ( pandas. Index or list - like ): The Index to assign. axis ( string or int ): The axis to reassign. inplace ( bool ): Whether to make these modifications inplace. Returns: If inplace is False returns a new DataFrame otherwise None.
def set_axis(self, labels, axis=0, inplace=None): """Assign desired index to given axis. Args: labels (pandas.Index or list-like): The Index to assign. axis (string or int): The axis to reassign. inplace (bool): Whether to make these modifications inplace. ...
Sort a DataFrame by one of the indices ( columns or index ). Args: axis: The axis to sort over. level: The MultiIndex level to sort over. ascending: Ascending or descending inplace: Whether or not to update this DataFrame inplace. kind: How to perform the sort. na_position: Where to position NA on the sort. sort_remain...
def sort_index( self, axis=0, level=None, ascending=True, inplace=False, kind="quicksort", na_position="last", sort_remaining=True, by=None, ): """Sort a DataFrame by one of the indices (columns or index). Args: ...
Sorts by a column/ row or list of columns/ rows. Args: by: A list of labels for the axis to sort over. axis: The axis to sort. ascending: Sort in ascending or descending order. inplace: If true do the operation inplace. kind: How to sort. na_position: Where to put np. nan values. Returns: A sorted DataFrame.
def sort_values( self, by, axis=0, ascending=True, inplace=False, kind="quicksort", na_position="last", ): """Sorts by a column/row or list of columns/rows. Args: by: A list of labels for the axis to sort over. ...
Subtract a DataFrame/ Series/ scalar from this DataFrame. Args: other: The object to use to apply the subtraction to this. axis: The axis to apply the subtraction over. level: Mutlilevel index level to subtract over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the subtraciont applied.
def sub(self, other, axis="columns", level=None, fill_value=None): """Subtract a DataFrame/Series/scalar from this DataFrame. Args: other: The object to use to apply the subtraction to this. axis: The axis to apply the subtraction over. level: Mutlilevel index ...
Convert the DataFrame to a NumPy array. Args: dtype: The dtype to pass to numpy. asarray () copy: Whether to ensure that the returned value is a not a view on another array. Returns: A numpy array.
def to_numpy(self, dtype=None, copy=False): """Convert the DataFrame to a NumPy array. Args: dtype: The dtype to pass to numpy.asarray() copy: Whether to ensure that the returned value is a not a view on another array. Returns: A num...
Divides this DataFrame against another DataFrame/ Series/ scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index level to apply divide over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Divide applied.
def truediv(self, other, axis="columns", level=None, fill_value=None): """Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index...
Computes variance across the DataFrame. Args: axis ( int ): The axis to take the variance on. skipna ( bool ): True to skip NA values false otherwise. ddof ( int ): degrees of freedom Returns: The variance of the DataFrame.
def var( self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs ): """Computes variance across the DataFrame. Args: axis (int): The axis to take the variance on. skipna (bool): True to skip NA values, false otherwise. ddof (...
Get the number of elements in the DataFrame. Returns: The number of elements in the DataFrame.
def size(self): """Get the number of elements in the DataFrame. Returns: The number of elements in the DataFrame. """ return len(self._query_compiler.index) * len(self._query_compiler.columns)
Flushes the call_queue and returns the data.
def get(self): """Flushes the call_queue and returns the data. Note: Since this object is a simple wrapper, just return the data. Returns: The object that was `put`. """ if self.call_queue: return self.apply(lambda df: df).data else: ...
Apply some callable function to the data in this partition.
def apply(self, func, **kwargs): """Apply some callable function to the data in this partition. Note: It is up to the implementation how kwargs are handled. They are an important part of many implementations. As of right now, they are not serialized. Args: f...
Apply some callable function to the data in this partition.
def apply(self, func, **kwargs): """Apply some callable function to the data in this partition. Note: It is up to the implementation how kwargs are handled. They are an important part of many implementations. As of right now, they are not serialized. Args: f...
Add the function to the apply function call stack.
def add_to_apply_calls(self, func, **kwargs): """Add the function to the apply function call stack. This function will be executed when apply is called. It will be executed in the order inserted; apply's func operates the last and return """ import dask self.delayed_cal...
Use a Ray task to read a chunk of a CSV into a pyarrow Table. Note: Ray functions are not detected by codecov ( thus pragma: no cover ) Args: fname: The filename of the file to open. num_splits: The number of splits ( partitions ) to separate the DataFrame into. start: The start byte offset. end: The end byte offset. k...
def _read_csv_with_offset_pyarrow_on_ray( fname, num_splits, start, end, kwargs, header ): # pragma: no cover """Use a Ray task to read a chunk of a CSV into a pyarrow Table. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: fname: The filename of the file to open....
Computes the number of rows and/ or columns to include in each partition.
def compute_chunksize(df, num_splits, default_block_size=32, axis=None): """Computes the number of rows and/or columns to include in each partition. Args: df: The DataFrame to split. num_splits: The maximum number of splits to separate the DataFrame into. default_block_size: Minimum num...
A memory efficient way to get a block of NaNs.
def _get_nan_block_id(partition_class, n_row=1, n_col=1, transpose=False): """A memory efficient way to get a block of NaNs. Args: partition_class (BaseFramePartition): The class to use to put the object in the remote format. n_row(int): The number of rows. n_col(int): The n...
Split the Pandas result evenly based on the provided number of splits.
def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None): """Split the Pandas result evenly based on the provided number of splits. Args: axis: The axis to split across. num_splits: The number of even splits to create. result: The result of the computation. This ...
Unpack the user input for getitem and setitem and compute ndim
def _parse_tuple(tup): """Unpack the user input for getitem and setitem and compute ndim loc[a] -> ([a], :), 1D loc[[a,b],] -> ([a,b], :), loc[a,b] -> ([a], [b]), 0D """ row_loc, col_loc = slice(None), slice(None) if is_tuple(tup): row_loc = tup[0] if len(tup) == 2: ...
Determine if a locator will enlarge the global index.
def _is_enlargement(locator, global_index): """Determine if a locator will enlarge the global index. Enlargement happens when you trying to locate using labels isn't in the original index. In other words, enlargement == adding NaNs ! """ if ( is_list_like(locator) and not is_slice(l...
Compute the ndim of result from locators
def _compute_ndim(row_loc, col_loc): """Compute the ndim of result from locators """ row_scaler = is_scalar(row_loc) col_scaler = is_scalar(col_loc) if row_scaler and col_scaler: ndim = 0 elif row_scaler ^ col_scaler: ndim = 1 else: ndim = 2 return ndim
Use numpy to broadcast or reshape item.
def _broadcast_item(self, row_lookup, col_lookup, item, to_shape): """Use numpy to broadcast or reshape item. Notes: - Numpy is memory efficient, there shouldn't be performance issue. """ # It is valid to pass a DataFrame or Series to __setitem__ that is larger than ...
Perform remote write and replace blocks.
def _write_items(self, row_lookup, col_lookup, item): """Perform remote write and replace blocks. """ self.qc.write_items(row_lookup, col_lookup, item)
Handle Enlargement ( if there is one ).
def _handle_enlargement(self, row_loc, col_loc): """Handle Enlargement (if there is one). Returns: None """ if _is_enlargement(row_loc, self.qc.index) or _is_enlargement( col_loc, self.qc.columns ): _warn_enlargement() self.qc.enla...
Helper for _enlarge_axis compute common labels and extra labels.
def _compute_enlarge_labels(self, locator, base_index): """Helper for _enlarge_axis, compute common labels and extra labels. Returns: nan_labels: The labels needs to be added """ # base_index_type can be pd.Index or pd.DatetimeIndex # depending on user input and pan...
Splits the DataFrame read into smaller DataFrames and handles all edge cases.
def _split_result_for_readers(axis, num_splits, df): # pragma: no cover """Splits the DataFrame read into smaller DataFrames and handles all edge cases. Args: axis: Which axis to split over. num_splits: The number of splits to create. df: The DataFrame after it has been read. Retu...
Use a Ray task to read columns from Parquet into a Pandas DataFrame.
def _read_parquet_columns(path, columns, num_splits, kwargs): # pragma: no cover """Use a Ray task to read columns from Parquet into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path: The path of the Parquet file. columns: The list of c...
Use a Ray task to read a chunk of a CSV into a Pandas DataFrame.
def _read_csv_with_offset_pandas_on_ray( fname, num_splits, start, end, kwargs, header ): # pragma: no cover """Use a Ray task to read a chunk of a CSV into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: fname: The filename of the file to ope...
Use a Ray task to read columns from HDF5 into a Pandas DataFrame.
def _read_hdf_columns(path_or_buf, columns, num_splits, kwargs): # pragma: no cover """Use a Ray task to read columns from HDF5 into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path_or_buf: The path of the HDF5 file. columns: The list ...
Use a Ray task to read columns from Feather into a Pandas DataFrame.
def _read_feather_columns(path, columns, num_splits): # pragma: no cover """Use a Ray task to read columns from Feather into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path: The path of the Feather file. columns: The list of column na...
Use a Ray task to read a chunk of SQL source.
def _read_sql_with_limit_offset( num_splits, sql, con, index_col, kwargs ): # pragma: no cover """Use a Ray task to read a chunk of SQL source. Note: Ray functions are not detected by codecov (thus pragma: no cover) """ pandas_df = pandas.read_sql(sql, con, index_col=index_col, **kwargs) if in...
Get the index from the indices returned by the workers.
def get_index(index_name, *partition_indices): # pragma: no cover """Get the index from the indices returned by the workers. Note: Ray functions are not detected by codecov (thus pragma: no cover)""" index = partition_indices[0].append(partition_indices[1:]) index.names = index_name return index
Load a parquet object from the file path returning a DataFrame. Ray DataFrame only supports pyarrow engine for now.
def read_parquet(cls, path, engine, columns, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the parquet file. We only support local files for now. ...
Constructs a DataFrame from a CSV file.
def _read_csv_from_file_pandas_on_ray(cls, filepath, kwargs={}): """Constructs a DataFrame from a CSV file. Args: filepath (str): path to the CSV file. npartitions (int): number of partitions for the DataFrame. kwargs (dict): args excluding filepath provided to read_...
Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas. read_csv
def _read(cls, filepath_or_buffer, **kwargs): """Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv """ # The ...
Load a h5 file from the file path or buffer returning a DataFrame.
def read_hdf(cls, path_or_buf, **kwargs): """Load a h5 file from the file path or buffer, returning a DataFrame. Args: path_or_buf: string, buffer or path object Path to the file to open, or an open :class:`pandas.HDFStore` object. kwargs: Pass into pandas.read_h...
Read a pandas. DataFrame from Feather format. Ray DataFrame only supports pyarrow engine for now.
def read_feather(cls, path, columns=None, use_threads=True): """Read a pandas.DataFrame from Feather format. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the feather file. We only support local files for now. mu...
Write records stored in a DataFrame to a SQL database. Args: qc: the query compiler of the DF that we want to run to_sql on kwargs: parameters for pandas. to_sql ( ** kwargs )
def to_sql(cls, qc, **kwargs): """Write records stored in a DataFrame to a SQL database. Args: qc: the query compiler of the DF that we want to run to_sql on kwargs: parameters for pandas.to_sql(**kwargs) """ # we first insert an empty DF in order to create the fu...
Reads a SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable ( select or text object ) SQL query to be executed or a table name. con: SQLAlchemy connectable ( engine/ connection ) or database string URI or DBAPI2 connection ( fallback mode ) index_col: Column ( s ) to set as index ( ...
def read_sql(cls, sql, con, index_col=None, **kwargs): """Reads a SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connect...
Convert the arg to datetime format. If not Ray DataFrame this falls back on pandas.
def to_datetime( arg, errors="raise", dayfirst=False, yearfirst=False, utc=None, box=True, format=None, exact=True, unit=None, infer_datetime_format=False, origin="unix", cache=False, ): """Convert the arg to datetime format. If not Ray DataFrame, this falls ba...
Read SQL query or database table into a DataFrame.
def read_sql( sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, partition_column=None, lower_bound=None, upper_bound=None, max_sessions=None, ): """ Read SQL query or database table into a DataFrame. Args: ...
Gets the lengths of the blocks.
def block_lengths(self): """Gets the lengths of the blocks. Note: This works with the property structure `_lengths_cache` to avoid having to recompute these values each time they are needed. """ if self._lengths_cache is None: try: # The first col...
Gets the widths of the blocks.
def block_widths(self): """Gets the widths of the blocks. Note: This works with the property structure `_widths_cache` to avoid having to recompute these values each time they are needed. """ if self._widths_cache is None: try: # The first column ...
Deploy a function to a partition in Ray.
def deploy_ray_func(func, partition, kwargs): # pragma: no cover """Deploy a function to a partition in Ray. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: func: The function to apply. partition: The partition to apply the function to. kwargs: A dict...
Gets the object out of the plasma store.
def get(self): """Gets the object out of the plasma store. Returns: The object from the plasma store. """ if len(self.call_queue): return self.apply(lambda x: x).get() try: return ray.get(self.oid) except RayTaskError as e: ...
Gets the lengths of the blocks.
def block_lengths(self): """Gets the lengths of the blocks. Note: This works with the property structure `_lengths_cache` to avoid having to recompute these values each time they are needed. """ if self._lengths_cache is None: # The first column will have the cor...
Gets the widths of the blocks.
def block_widths(self): """Gets the widths of the blocks. Note: This works with the property structure `_widths_cache` to avoid having to recompute these values each time they are needed. """ if self._widths_cache is None: # The first column will have the correct...
Applies map_func to every partition.
def map_across_blocks(self, map_func): """Applies `map_func` to every partition. Args: map_func: The function to apply. Returns: A new BaseFrameManager object, the type of object that called this. """ preprocessed_map_func = self.preprocess_func(map_func...
Copartition two BlockPartitions objects.
def copartition_datasets(self, axis, other, left_func, right_func): """Copartition two BlockPartitions objects. Args: axis: The axis to copartition. other: The other BlockPartitions object to copartition with. left_func: The function to apply to left. If None, just u...
Applies map_func to every partition.
def map_across_full_axis(self, axis, map_func): """Applies `map_func` to every partition. Note: This method should be used in the case that `map_func` relies on some global information about the axis. Args: axis: The axis to perform the map across (0 - index, 1 - column...
Take the first ( or last ) n rows or columns from the blocks
def take(self, axis, n): """Take the first (or last) n rows or columns from the blocks Note: Axis = 0 will be equivalent to `head` or `tail` Axis = 1 will be equivalent to `front` or `back` Args: axis: The axis to extract (0 for extracting rows, 1 for extracting colum...
Concatenate the blocks with another set of blocks.
def concat(self, axis, other_blocks): """Concatenate the blocks with another set of blocks. Note: Assumes that the blocks are already the same shape on the dimension being concatenated. A ValueError will be thrown if this condition is not met. Args: axis: Th...
Convert this object into a Pandas DataFrame from the partitions.
def to_pandas(self, is_transposed=False): """Convert this object into a Pandas DataFrame from the partitions. Args: is_transposed: A flag for telling this object that the external representation is transposed, but not the internal. Returns: A Pandas Data...
This gets the internal indices stored in the partitions.
def get_indices(self, axis=0, index_func=None, old_blocks=None): """This gets the internal indices stored in the partitions. Note: These are the global indices of the object. This is mostly useful when you have deleted rows/columns internally, but do not know which ones were del...
Convert a global index to a block index and local index.
def _get_blocks_containing_index(self, axis, index): """Convert a global index to a block index and local index. Note: This method is primarily used to convert a global index into a partition index (along the axis provided) and local index (useful for `iloc` or similar operation...
Convert indices to a dict of block index to internal index mapping.
def _get_dict_of_block_index(self, axis, indices, ordered=False): """Convert indices to a dict of block index to internal index mapping. Note: See `_get_blocks_containing_index` for primary usage. This method accepts a list of indices rather than just a single value, and uses `_...
Applies a function to a list of remote partitions.
def _apply_func_to_list_of_partitions(self, func, partitions, **kwargs): """Applies a function to a list of remote partitions. Note: The main use for this is to preprocess the func. Args: func: The func to apply partitions: The list of partitions Returns: ...
Applies a function to select indices.
def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False): """Applies a function to select indices. Note: Your internal function must take a kwarg `internal_indices` for this to work correctly. This prevents information leakage of the internal index to th...
Applies a function to a select subset of full columns/ rows.
def apply_func_to_select_indices_along_full_axis( self, axis, func, indices, keep_remaining=False ): """Applies a function to a select subset of full columns/rows. Note: This should be used when you need to apply a function that relies on some global information for the entire c...
Apply a function to along both axis
def apply_func_to_indices_both_axis( self, func, row_indices, col_indices, lazy=False, keep_remaining=True, mutate=False, item_to_distribute=None, ): """ Apply a function to along both axis Important: For your func to operate d...
Apply a function that requires two BaseFrameManager objects.
def inter_data_operation(self, axis, func, other): """Apply a function that requires two BaseFrameManager objects. Args: axis: The axis to apply the function over (0 - rows, 1 - columns) func: The function to apply other: The other BaseFrameManager object to apply fu...
Shuffle the partitions based on the shuffle_func.
def manual_shuffle(self, axis, shuffle_func, lengths): """Shuffle the partitions based on the `shuffle_func`. Args: axis: The axis to shuffle across. shuffle_func: The function to apply before splitting the result. lengths: The length of each partition to split the r...
Load a parquet object from the file path returning a DataFrame.
def read_parquet(path, engine="auto", columns=None, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Args: path: The filepath of the parquet file. We only support local files for now. engine: This argument doesn't do anything for now. kwargs: ...
Creates a parser function from the given sep.
def _make_parser_func(sep): """Creates a parser function from the given sep. Args: sep: The separator default to use for the parser. Returns: A function object. """ def parser_func( filepath_or_buffer, sep=sep, delimiter=None, header="infer", ...
Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas. read_csv
def _read(**kwargs): """Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv """ pd_obj = BaseFactory.read_csv(**kwargs) # This happens when...
Read SQL query or database table into a DataFrame.
def read_sql( sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, ): """ Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed o...
Load a parquet object from the file path returning a DataFrame. Ray DataFrame only supports pyarrow engine for now.
def read_parquet(cls, path, engine, columns, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the parquet file. We only support local files for now. ...
Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas. read_csv
def _read(cls, **kwargs): """Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv """ pd_obj = pandas.read_csv(*...
Make a feature mask of categorical features in X.
def auto_select_categorical_features(X, threshold=10): """Make a feature mask of categorical features in X. Features with less than 10 unique values are considered categorical. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix...
Split X into selected features and other features
def _X_selected(X, selected): """Split X into selected features and other features""" n_features = X.shape[1] ind = np.arange(n_features) sel = np.zeros(n_features, dtype=bool) sel[np.asarray(selected)] = True non_sel = np.logical_not(sel) n_selected = np.sum(sel) X_sel = X[:, ind[sel]] ...
Apply a transform function to portion of selected features.
def _transform_selected(X, transform, selected, copy=True): """Apply a transform function to portion of selected features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. transform : callable A callable transform(X)...
Adjust all values in X to encode for NaNs and infinities in the data.
def _matrix_adjust(self, X): """Adjust all values in X to encode for NaNs and infinities in the data. Parameters ---------- X : array-like, shape=(n_samples, n_feature) Input array of type int. Returns ------- X : array-like, shape=(n_samples, n_feat...
Assume X contains only categorical features.
def _fit_transform(self, X): """Assume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array( ...
Fit OneHotEncoder to X then transform X.
def fit_transform(self, X, y=None): """Fit OneHotEncoder to X, then transform X. Equivalent to self.fit(X).transform(X), but more convenient and more efficient. See fit for the parameters, transform for the return value. Parameters ---------- X : array-like or sparse ma...
Asssume X contains only categorical features.
def _transform(self, X): """Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array(X, accept_spar...
Transform X using one - hot encoding.
def transform(self, X): """Transform X using one-hot encoding. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. Returns ------- X_out : sparse matrix if sparse=True else a 2-d array, d...
Fit an optimized machine learning pipeline.
def fit(self, features, target, sample_weight=None, groups=None): """Fit an optimized machine learning pipeline. Uses genetic programming to optimize a machine learning pipeline that maximizes score on the provided features and target. Performs internal k-fold cross-validaton to avoid o...
Setup Memory object for memory caching.
def _setup_memory(self): """Setup Memory object for memory caching. """ if self.memory: if isinstance(self.memory, str): if self.memory == "auto": # Create a temporary folder to store the transformers of the pipeline self._cache...
Helper function to update the _optimized_pipeline field.
def _update_top_pipeline(self): """Helper function to update the _optimized_pipeline field.""" # Store the pipeline with the highest internal testing score if self._pareto_front: self._optimized_pipeline_score = -float('inf') for pipeline, pipeline_scores in zip(self._par...
Print out best pipeline at the end of optimization process.
def _summary_of_best_pipeline(self, features, target): """Print out best pipeline at the end of optimization process. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix target: array-like {n_samples} List of class labels fo...