Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def sort_index(
self,
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
by=None,
):
axis = self._get_axis_numb... | [
"Sort a DataFrame by one of the indices (columns or index).\r\n\r\n Args:\r\n axis: The axis to sort over.\r\n level: The MultiIndex level to sort over.\r\n ascending: Ascending or descending\r\n inplace: Whether or not to update this DataFrame inplace.\r\n ... |
Please provide a description of the function:def sort_values(
self,
by,
axis=0,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
):
axis = self._get_axis_number(axis)
if not is_list_like(by):
... | [
"Sorts by a column/row or list of columns/rows.\r\n\r\n Args:\r\n by: A list of labels for the axis to sort over.\r\n axis: The axis to sort.\r\n ascending: Sort in ascending or descending order.\r\n inplace: If true, do the operation inplace.\r\n kind: ... |
Please provide a description of the function:def sub(self, other, axis="columns", level=None, fill_value=None):
return self._binary_op(
"sub", other, axis=axis, level=level, fill_value=fill_value
) | [
"Subtract a DataFrame/Series/scalar from this DataFrame.\r\n\r\n Args:\r\n other: The object to use to apply the subtraction to this.\r\n axis: The axis to apply the subtraction over.\r\n level: Mutlilevel index level to subtract over.\r\n fill_value: The value to ... |
Please provide a description of the function:def to_numpy(self, dtype=None, copy=False):
return self._default_to_pandas("to_numpy", dtype=dtype, copy=copy) | [
"Convert the DataFrame to a NumPy array.\r\n\r\n Args:\r\n dtype: The dtype to pass to numpy.asarray()\r\n copy: Whether to ensure that the returned value is a not a view on another\r\n array.\r\n\r\n Returns:\r\n A numpy array.\r\n "
] |
Please provide a description of the function:def truediv(self, other, axis="columns", level=None, fill_value=None):
return self._binary_op(
"truediv", other, axis=axis, level=level, fill_value=fill_value
) | [
"Divides this DataFrame against another DataFrame/Series/scalar.\r\n\r\n Args:\r\n other: The object to use to apply the divide against this.\r\n axis: The axis to divide over.\r\n level: The Multilevel index level to apply divide over.\r\n fill_value: The value to... |
Please provide a description of the function:def var(
self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs
):
axis = self._get_axis_number(axis) if axis is not None else 0
if numeric_only is not None and not numeric_only:
self._validate_dty... | [
"Computes variance across the DataFrame.\r\n\r\n Args:\r\n axis (int): The axis to take the variance on.\r\n skipna (bool): True to skip NA values, false otherwise.\r\n ddof (int): degrees of freedom\r\n\r\n Returns:\r\n The variance of the DataFrame.\r\n ... |
Please provide a description of the function:def size(self):
return len(self._query_compiler.index) * len(self._query_compiler.columns) | [
"Get the number of elements in the DataFrame.\r\n\r\n Returns:\r\n The number of elements in the DataFrame.\r\n "
] |
Please provide a description of the function:def get(self):
if self.call_queue:
return self.apply(lambda df: df).data
else:
return self.data.copy() | [
"Flushes the call_queue and returns the data.\n\n Note: Since this object is a simple wrapper, just return the data.\n\n Returns:\n The object that was `put`.\n "
] |
Please provide a description of the function:def apply(self, func, **kwargs):
self.call_queue.append((func, kwargs))
def call_queue_closure(data, call_queues):
result = data.copy()
for func, kwargs in call_queues:
try:
result = func(r... | [
"Apply some callable function to the data in this partition.\n\n Note: It is up to the implementation how kwargs are handled. They are\n an important part of many implementations. As of right now, they\n are not serialized.\n\n Args:\n func: The lambda to apply (may al... |
Please provide a description of the function:def apply(self, func, **kwargs):
import dask
# applies the func lazily
delayed_call = self.delayed_call
self.delayed_call = self.dask_obj
return self.__class__(dask.delayed(func)(delayed_call, **kwargs)) | [
"Apply some callable function to the data in this partition.\n\n Note: It is up to the implementation how kwargs are handled. They are\n an important part of many implementations. As of right now, they\n are not serialized.\n\n Args:\n func: The lambda to apply (may al... |
Please provide a description of the function:def add_to_apply_calls(self, func, **kwargs):
import dask
self.delayed_call = dask.delayed(func)(self.delayed_call, **kwargs)
return self | [
"Add the function to the apply function call stack.\n\n This function will be executed when apply is called. It will be executed\n in the order inserted; apply's func operates the last and return\n "
] |
Please provide a description of the function:def _read_csv_with_offset_pyarrow_on_ray(
fname, num_splits, start, end, kwargs, header
): # pragma: no cover
bio = open(fname, "rb")
# The header line for the CSV file
first_line = bio.readline()
bio.seek(start)
to_read = header + first_line + ... | [
"Use a Ray task to read a chunk of a CSV into a pyarrow Table.\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n Args:\n fname: The filename of the file to open.\n num_splits: The number of splits (partitions) to separate the DataFrame into.\n start: The start ... |
Please provide a description of the function:def compute_chunksize(df, num_splits, default_block_size=32, axis=None):
if axis == 0 or axis is None:
row_chunksize = get_default_chunksize(len(df.index), num_splits)
# Take the min of the default and the memory-usage chunksize first to avoid a
... | [
"Computes the number of rows and/or columns to include in each partition.\n\n Args:\n df: The DataFrame to split.\n num_splits: The maximum number of splits to separate the DataFrame into.\n default_block_size: Minimum number of rows/columns (default set to 32x32).\n axis: The axis to... |
Please provide a description of the function:def _get_nan_block_id(partition_class, n_row=1, n_col=1, transpose=False):
global _NAN_BLOCKS
if transpose:
n_row, n_col = n_col, n_row
shape = (n_row, n_col)
if shape not in _NAN_BLOCKS:
arr = np.tile(np.array(np.NaN), shape)
# T... | [
"A memory efficient way to get a block of NaNs.\n\n Args:\n partition_class (BaseFramePartition): The class to use to put the object\n in the remote format.\n n_row(int): The number of rows.\n n_col(int): The number of columns.\n transpose(bool): If true, swap rows and colu... |
Please provide a description of the function:def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None):
if num_splits == 1:
return result
if length_list is not None:
length_list.insert(0, 0)
sums = np.cumsum(length_list)
if axis == 0:
retur... | [
"Split the Pandas result evenly based on the provided number of splits.\n\n Args:\n axis: The axis to split across.\n num_splits: The number of even splits to create.\n result: The result of the computation. This should be a Pandas\n DataFrame.\n length_list: The list of le... |
Please provide a description of the function:def _parse_tuple(tup):
row_loc, col_loc = slice(None), slice(None)
if is_tuple(tup):
row_loc = tup[0]
if len(tup) == 2:
col_loc = tup[1]
if len(tup) > 2:
raise IndexingError("Too many indexers")
else:
... | [
"Unpack the user input for getitem and setitem and compute ndim\n\n loc[a] -> ([a], :), 1D\n loc[[a,b],] -> ([a,b], :),\n loc[a,b] -> ([a], [b]), 0D\n "
] |
Please provide a description of the function:def _is_enlargement(locator, global_index):
if (
is_list_like(locator)
and not is_slice(locator)
and len(locator) > 0
and not is_boolean_array(locator)
and (isinstance(locator, type(global_index[0])) and locator not in global_... | [
"Determine if a locator will enlarge the global index.\n\n Enlargement happens when you trying to locate using labels isn't in the\n original index. In other words, enlargement == adding NaNs !\n "
] |
Please provide a description of the function:def _compute_ndim(row_loc, col_loc):
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 | [
"Compute the ndim of result from locators\n "
] |
Please provide a description of the function:def _broadcast_item(self, row_lookup, col_lookup, item, to_shape):
# It is valid to pass a DataFrame or Series to __setitem__ that is larger than
# the target the user is trying to overwrite. This
if isinstance(item, (pandas.Series, pandas.Da... | [
"Use numpy to broadcast or reshape item.\n\n Notes:\n - Numpy is memory efficient, there shouldn't be performance issue.\n "
] |
Please provide a description of the function:def _write_items(self, row_lookup, col_lookup, item):
self.qc.write_items(row_lookup, col_lookup, item) | [
"Perform remote write and replace blocks.\n "
] |
Please provide a description of the function:def _handle_enlargement(self, row_loc, col_loc):
if _is_enlargement(row_loc, self.qc.index) or _is_enlargement(
col_loc, self.qc.columns
):
_warn_enlargement()
self.qc.enlarge_partitions(
new_row_la... | [
"Handle Enlargement (if there is one).\n\n Returns:\n None\n "
] |
Please provide a description of the function:def _compute_enlarge_labels(self, locator, base_index):
# base_index_type can be pd.Index or pd.DatetimeIndex
# depending on user input and pandas behavior
# See issue #2264
base_index_type = type(base_index)
locator_as_index ... | [
"Helper for _enlarge_axis, compute common labels and extra labels.\n\n Returns:\n nan_labels: The labels needs to be added\n "
] |
Please provide a description of the function:def _split_result_for_readers(axis, num_splits, df): # pragma: no cover
splits = split_result_of_axis_func_pandas(axis, num_splits, df)
if not isinstance(splits, list):
splits = [splits]
return splits | [
"Splits the DataFrame read into smaller DataFrames and handles all edge cases.\n\n Args:\n axis: Which axis to split over.\n num_splits: The number of splits to create.\n df: The DataFrame after it has been read.\n\n Returns:\n A list of pandas DataFrames.\n "
] |
Please provide a description of the function:def _read_parquet_columns(path, columns, num_splits, kwargs): # pragma: no cover
import pyarrow.parquet as pq
df = pq.read_pandas(path, columns=columns, **kwargs).to_pandas()
# Append the length of the index here to build it externally
return _split_re... | [
"Use a Ray task to read columns from Parquet into a Pandas DataFrame.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n\n Args:\n path: The path of the Parquet file.\n columns: The list of column names to read.\n num_splits: The number of partitions to split th... |
Please provide a description of the function:def _read_csv_with_offset_pandas_on_ray(
fname, num_splits, start, end, kwargs, header
): # pragma: no cover
index_col = kwargs.get("index_col", None)
bio = file_open(fname, "rb")
bio.seek(start)
to_read = header + bio.read(end - start)
bio.clos... | [
"Use a Ray task to read a chunk of a CSV into a Pandas DataFrame.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n\n Args:\n fname: The filename of the file to open.\n num_splits: The number of splits (partitions) to separate the DataFrame into.\n start: The s... |
Please provide a description of the function:def _read_hdf_columns(path_or_buf, columns, num_splits, kwargs): # pragma: no cover
df = pandas.read_hdf(path_or_buf, columns=columns, **kwargs)
# Append the length of the index here to build it externally
return _split_result_for_readers(0, num_splits, df... | [
"Use a Ray task to read columns from HDF5 into a Pandas DataFrame.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n\n Args:\n path_or_buf: The path of the HDF5 file.\n columns: The list of column names to read.\n num_splits: The number of partitions to split t... |
Please provide a description of the function:def _read_feather_columns(path, columns, num_splits): # pragma: no cover
from pyarrow import feather
df = feather.read_feather(path, columns=columns)
# Append the length of the index here to build it externally
return _split_result_for_readers(0, num_s... | [
"Use a Ray task to read columns from Feather into a Pandas DataFrame.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n\n Args:\n path: The path of the Feather file.\n columns: The list of column names to read.\n num_splits: The number of partitions to split th... |
Please provide a description of the function:def _read_sql_with_limit_offset(
num_splits, sql, con, index_col, kwargs
): # pragma: no cover
pandas_df = pandas.read_sql(sql, con, index_col=index_col, **kwargs)
if index_col is None:
index = len(pandas_df)
else:
index = pandas_df.inde... | [
"Use a Ray task to read a chunk of SQL source.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n "
] |
Please provide a description of the function:def get_index(index_name, *partition_indices): # pragma: no cover
index = partition_indices[0].append(partition_indices[1:])
index.names = index_name
return index | [
"Get the index from the indices returned by the workers.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)"
] |
Please provide a description of the function:def read_parquet(cls, path, engine, columns, **kwargs):
from pyarrow.parquet import ParquetFile
if cls.read_parquet_remote_task is None:
return super(RayIO, cls).read_parquet(path, engine, columns, **kwargs)
if not columns:
... | [
"Load a parquet object from the file path, returning a DataFrame.\n Ray DataFrame only supports pyarrow engine for now.\n\n Args:\n path: The filepath of the parquet file.\n We only support local files for now.\n engine: Ray only support pyarrow reader.\n ... |
Please provide a description of the function:def _read_csv_from_file_pandas_on_ray(cls, filepath, kwargs={}):
names = kwargs.get("names", None)
index_col = kwargs.get("index_col", None)
if names is None:
# For the sake of the empty df, we assume no `index_col` to get the cor... | [
"Constructs a DataFrame from a CSV file.\n\n Args:\n filepath (str): path to the CSV file.\n npartitions (int): number of partitions for the DataFrame.\n kwargs (dict): args excluding filepath provided to read_csv.\n\n Returns:\n DataFrame or Series construc... |
Please provide a description of the function:def _read(cls, filepath_or_buffer, **kwargs):
# The intention of the inspection code is to reduce the amount of
# communication we have to do between processes and nodes. We take a quick
# pass over the arguments and remove those that are def... | [
"Read csv file from local disk.\n Args:\n filepath_or_buffer:\n The filepath of the csv file.\n We only support local files for now.\n kwargs: Keyword arguments in pandas.read_csv\n "
] |
Please provide a description of the function:def read_hdf(cls, path_or_buf, **kwargs):
if cls.read_hdf_remote_task is None:
return super(RayIO, cls).read_hdf(path_or_buf, **kwargs)
format = cls._validate_hdf_format(path_or_buf=path_or_buf)
if format is None:
Er... | [
"Load a h5 file from the file path or buffer, returning a DataFrame.\n\n Args:\n path_or_buf: string, buffer or path object\n Path to the file to open, or an open :class:`pandas.HDFStore` object.\n kwargs: Pass into pandas.read_hdf function.\n\n Returns:\n ... |
Please provide a description of the function:def read_feather(cls, path, columns=None, use_threads=True):
if cls.read_feather_remote_task is None:
return super(RayIO, cls).read_feather(
path, columns=columns, use_threads=use_threads
)
if columns is None:... | [
"Read a pandas.DataFrame from Feather format.\n Ray DataFrame only supports pyarrow engine for now.\n\n Args:\n path: The filepath of the feather file.\n We only support local files for now.\n multi threading is set to True by default\n columns:... |
Please provide a description of the function:def to_sql(cls, qc, **kwargs):
# we first insert an empty DF in order to create the full table in the database
# This also helps to validate the input against pandas
# we would like to_sql() to complete only when all rows have been inserted i... | [
"Write records stored in a DataFrame to a SQL database.\n Args:\n qc: the query compiler of the DF that we want to run to_sql on\n kwargs: parameters for pandas.to_sql(**kwargs)\n "
] |
Please provide a description of the function:def read_sql(cls, sql, con, index_col=None, **kwargs):
if cls.read_sql_remote_task is None:
return super(RayIO, cls).read_sql(sql, con, index_col=index_col, **kwargs)
row_cnt_query = "SELECT COUNT(*) FROM ({})".format(sql)
row_cn... | [
"Reads a SQL query or database table into a DataFrame.\n Args:\n sql: string or SQLAlchemy Selectable (select or text object) SQL query to be\n executed or a table name.\n con: SQLAlchemy connectable (engine/connection) or database string URI or\n DBAPI2 co... |
Please provide a description of the function: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,
):
if not isinstance(arg, DataFram... | [
"Convert the arg to datetime format. If not Ray DataFrame, this falls\n back on pandas.\n\n Args:\n errors ('raise' or 'ignore'): If 'ignore', errors are silenced.\n Pandas blatantly ignores this argument so we will too.\n dayfirst (bool): Date format is passed in as day first.\n ... |
Please provide a description of the function: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,
):
_, _, _, kwargs =... | [
" Read SQL query or database table into a DataFrame.\n\n Args:\n sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name.\n con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode)\n index_col: C... |
Please provide a description of the function:def block_lengths(self):
if self._lengths_cache is None:
try:
# The first column will have the correct lengths. We have an
# invariant that requires that all blocks be the same length in a
# row of ... | [
"Gets the lengths of the blocks.\n\n Note: This works with the property structure `_lengths_cache` to avoid\n having to recompute these values each time they are needed.\n "
] |
Please provide a description of the function:def block_widths(self):
if self._widths_cache is None:
try:
# The first column will have the correct lengths. We have an
# invariant that requires that all blocks be the same width in a
# column of ... | [
"Gets the widths of the blocks.\n\n Note: This works with the property structure `_widths_cache` to avoid\n having to recompute these values each time they are needed.\n "
] |
Please provide a description of the function:def deploy_ray_func(func, partition, kwargs): # pragma: no cover
try:
return func(partition, **kwargs)
# Sometimes Arrow forces us to make a copy of an object before we operate
# on it. We don't want the error to propagate to the user, and we want t... | [
"Deploy a function to a partition in Ray.\n\n Note: Ray functions are not detected by codecov (thus pragma: no cover)\n\n Args:\n func: The function to apply.\n partition: The partition to apply the function to.\n kwargs: A dictionary of keyword arguments for the function.\n\n Returns:... |
Please provide a description of the function:def get(self):
if len(self.call_queue):
return self.apply(lambda x: x).get()
try:
return ray.get(self.oid)
except RayTaskError as e:
handle_ray_task_error(e) | [
"Gets the object out of the plasma store.\n\n Returns:\n The object from the plasma store.\n "
] |
Please provide a description of the function:def block_lengths(self):
if self._lengths_cache is None:
# The first column will have the correct lengths. We have an
# invariant that requires that all blocks be the same length in a
# row of blocks.
self._len... | [
"Gets the lengths of the blocks.\n\n Note: This works with the property structure `_lengths_cache` to avoid\n having to recompute these values each time they are needed.\n "
] |
Please provide a description of the function:def block_widths(self):
if self._widths_cache is None:
# The first column will have the correct lengths. We have an
# invariant that requires that all blocks be the same width in a
# column of blocks.
self._wid... | [
"Gets the widths of the blocks.\n\n Note: This works with the property structure `_widths_cache` to avoid\n having to recompute these values each time they are needed.\n "
] |
Please provide a description of the function:def map_across_blocks(self, map_func):
preprocessed_map_func = self.preprocess_func(map_func)
new_partitions = np.array(
[
[part.apply(preprocessed_map_func) for part in row_of_parts]
for row_of_parts in se... | [
"Applies `map_func` to every partition.\n\n Args:\n map_func: The function to apply.\n\n Returns:\n A new BaseFrameManager object, the type of object that called this.\n "
] |
Please provide a description of the function:def copartition_datasets(self, axis, other, left_func, right_func):
if left_func is None:
new_self = self
else:
new_self = self.map_across_full_axis(axis, left_func)
# This block of code will only shuffle if absolutel... | [
"Copartition two BlockPartitions objects.\n\n Args:\n axis: The axis to copartition.\n other: The other BlockPartitions object to copartition with.\n left_func: The function to apply to left. If None, just use the dimension\n of self (based on axis).\n ... |
Please provide a description of the function:def map_across_full_axis(self, axis, map_func):
# Since we are already splitting the DataFrame back up after an
# operation, we will just use this time to compute the number of
# partitions as best we can right now.
num_splits = self.... | [
"Applies `map_func` to every partition.\n\n Note: This method should be used in the case that `map_func` relies on\n some global information about the axis.\n\n Args:\n axis: The axis to perform the map across (0 - index, 1 - columns).\n map_func: The function to apply... |
Please provide a description of the function:def take(self, axis, n):
# These are the partitions that we will extract over
if not axis:
partitions = self.partitions
bin_lengths = self.block_lengths
else:
partitions = self.partitions.T
bin_... | [
"Take the first (or last) n rows or columns from the blocks\n\n Note: Axis = 0 will be equivalent to `head` or `tail`\n Axis = 1 will be equivalent to `front` or `back`\n\n Args:\n axis: The axis to extract (0 for extracting rows, 1 for extracting columns)\n n: The n... |
Please provide a description of the function:def concat(self, axis, other_blocks):
if type(other_blocks) is list:
other_blocks = [blocks.partitions for blocks in other_blocks]
return self.__constructor__(
np.concatenate([self.partitions] + other_blocks, axis=axis... | [
"Concatenate the blocks with another set of blocks.\n\n Note: Assumes that the blocks are already the same shape on the\n dimension being concatenated. A ValueError will be thrown if this\n condition is not met.\n\n Args:\n axis: The axis to concatenate to.\n ... |
Please provide a description of the function:def to_pandas(self, is_transposed=False):
# In the case this is transposed, it is easier to just temporarily
# transpose back then transpose after the conversion. The performance
# is the same as if we individually transposed the blocks and
... | [
"Convert this object into a Pandas DataFrame from the partitions.\n\n Args:\n is_transposed: A flag for telling this object that the external\n representation is transposed, but not the internal.\n\n Returns:\n A Pandas DataFrame\n "
] |
Please provide a description of the function:def get_indices(self, axis=0, index_func=None, old_blocks=None):
ErrorMessage.catch_bugs_and_request_email(not callable(index_func))
func = self.preprocess_func(index_func)
if axis == 0:
# We grab the first column of blocks and ex... | [
"This gets the internal indices stored in the partitions.\n\n Note: These are the global indices of the object. This is mostly useful\n when you have deleted rows/columns internally, but do not know\n which ones were deleted.\n\n Args:\n axis: This axis to extract the ... |
Please provide a description of the function:def _get_blocks_containing_index(self, axis, index):
if not axis:
ErrorMessage.catch_bugs_and_request_email(index > sum(self.block_widths))
cumulative_column_widths = np.array(self.block_widths).cumsum()
block_idx = int(np... | [
"Convert a global index to a block index and local index.\n\n Note: This method is primarily used to convert a global index into a\n partition index (along the axis provided) and local index (useful\n for `iloc` or similar operations.\n\n Args:\n axis: The axis along w... |
Please provide a description of the function:def _get_dict_of_block_index(self, axis, indices, ordered=False):
# Get the internal index and create a dictionary so we only have to
# travel to each partition once.
all_partitions_and_idx = [
self._get_blocks_containing_index(ax... | [
"Convert indices to a dict of block index to internal index mapping.\n\n Note: See `_get_blocks_containing_index` for primary usage. This method\n accepts a list of indices rather than just a single value, and uses\n `_get_blocks_containing_index`.\n\n Args:\n axis: Th... |
Please provide a description of the function:def _apply_func_to_list_of_partitions(self, func, partitions, **kwargs):
preprocessed_func = self.preprocess_func(func)
return [obj.apply(preprocessed_func, **kwargs) for obj in partitions] | [
"Applies a function to a list of remote partitions.\n\n Note: The main use for this is to preprocess the func.\n\n Args:\n func: The func to apply\n partitions: The list of partitions\n\n Returns:\n A list of BaseFramePartition objects.\n "
] |
Please provide a description of the function:def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False):
if self.partitions.size == 0:
return np.array([[]])
# Handling dictionaries has to be done differently, but we still want
# to figure out the parti... | [
"Applies a function to select indices.\n\n Note: Your internal function must take a kwarg `internal_indices` for\n this to work correctly. This prevents information leakage of the\n internal index to the external representation.\n\n Args:\n axis: The axis to apply the ... |
Please provide a description of the function:def apply_func_to_select_indices_along_full_axis(
self, axis, func, indices, keep_remaining=False
):
if self.partitions.size == 0:
return self.__constructor__(np.array([[]]))
if isinstance(indices, dict):
dict_indi... | [
"Applies a function to a select subset of full columns/rows.\n\n Note: This should be used when you need to apply a function that relies\n on some global information for the entire column/row, but only need\n to apply a function to a subset.\n\n Important: For your func to operat... |
Please provide a description of the function:def apply_func_to_indices_both_axis(
self,
func,
row_indices,
col_indices,
lazy=False,
keep_remaining=True,
mutate=False,
item_to_distribute=None,
):
if keep_remaining:
row_parti... | [
"\n Apply a function to along both axis\n\n Important: For your func to operate directly on the indices provided,\n it must use `row_internal_indices, col_internal_indices` as keyword\n arguments.\n "
] |
Please provide a description of the function:def inter_data_operation(self, axis, func, other):
if axis:
partitions = self.row_partitions
other_partitions = other.row_partitions
else:
partitions = self.column_partitions
other_partitions = other.co... | [
"Apply a function that requires two BaseFrameManager objects.\n\n Args:\n axis: The axis to apply the function over (0 - rows, 1 - columns)\n func: The function to apply\n other: The other BaseFrameManager object to apply func to.\n\n Returns:\n A new BaseFr... |
Please provide a description of the function:def manual_shuffle(self, axis, shuffle_func, lengths):
if axis:
partitions = self.row_partitions
else:
partitions = self.column_partitions
func = self.preprocess_func(shuffle_func)
result = np.array([part.shuff... | [
"Shuffle the partitions based on the `shuffle_func`.\n\n Args:\n axis: The axis to shuffle across.\n shuffle_func: The function to apply before splitting the result.\n lengths: The length of each partition to split the result into.\n\n Returns:\n A new Base... |
Please provide a description of the function:def read_parquet(path, engine="auto", columns=None, **kwargs):
return DataFrame(
query_compiler=BaseFactory.read_parquet(
path=path, columns=columns, engine=engine, **kwargs
)
) | [
"Load a parquet object from the file path, returning a DataFrame.\n\n Args:\n path: The filepath of the parquet file.\n We only support local files for now.\n engine: This argument doesn't do anything for now.\n kwargs: Pass into parquet's read_pandas function.\n "
] |
Please provide a description of the function:def _make_parser_func(sep):
def parser_func(
filepath_or_buffer,
sep=sep,
delimiter=None,
header="infer",
names=None,
index_col=None,
usecols=None,
squeeze=False,
prefix=None,
mangle_du... | [
"Creates a parser function from the given sep.\n\n Args:\n sep: The separator default to use for the parser.\n\n Returns:\n A function object.\n "
] |
Please provide a description of the function:def _read(**kwargs):
pd_obj = BaseFactory.read_csv(**kwargs)
# This happens when `read_csv` returns a TextFileReader object for iterating through
if isinstance(pd_obj, pandas.io.parsers.TextFileReader):
reader = pd_obj.read
pd_obj.read = lamb... | [
"Read csv file from local disk.\n Args:\n filepath_or_buffer:\n The filepath of the csv file.\n We only support local files for now.\n kwargs: Keyword arguments in pandas.read_csv\n "
] |
Please provide a description of the function:def read_sql(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize=None,
):
_, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
return DataFrame(query_compiler=BaseFactory.... | [
" Read SQL query or database table into a DataFrame.\n\n Args:\n sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name.\n con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode)\n index_col: C... |
Please provide a description of the function:def read_parquet(cls, path, engine, columns, **kwargs):
ErrorMessage.default_to_pandas("`read_parquet`")
return cls.from_pandas(pandas.read_parquet(path, engine, columns, **kwargs)) | [
"Load a parquet object from the file path, returning a DataFrame.\n Ray DataFrame only supports pyarrow engine for now.\n\n Args:\n path: The filepath of the parquet file.\n We only support local files for now.\n engine: Ray only support pyarrow reader.\n ... |
Please provide a description of the function:def _read(cls, **kwargs):
pd_obj = pandas.read_csv(**kwargs)
if isinstance(pd_obj, pandas.DataFrame):
return cls.from_pandas(pd_obj)
if isinstance(pd_obj, pandas.io.parsers.TextFileReader):
# Overwriting the read metho... | [
"Read csv file from local disk.\n Args:\n filepath_or_buffer:\n The filepath of the csv file.\n We only support local files for now.\n kwargs: Keyword arguments in pandas.read_csv\n "
] |
Please provide a description of the function:def auto_select_categorical_features(X, threshold=10):
feature_mask = []
for column in range(X.shape[1]):
if sparse.issparse(X):
indptr_start = X.indptr[column]
indptr_end = X.indptr[column + 1]
unique = np.unique(X.d... | [
"Make a feature mask of categorical features in X.\n\n Features with less than 10 unique values are considered categorical.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n Dense array or sparse matrix.\n\n threshold : int\n Maximum number o... |
Please provide a description of the function:def _X_selected(X, selected):
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]]
X_not_... | [
"Split X into selected features and other features"
] |
Please provide a description of the function:def _transform_selected(X, transform, selected, copy=True):
if selected == "all":
return transform(X)
if len(selected) == 0:
return X
X = check_array(X, accept_sparse='csc', force_all_finite=False)
X_sel, X_not_sel, n_selected, n_featur... | [
"Apply a transform function to portion of selected features.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n Dense array or sparse matrix.\n\n transform : callable\n A callable transform(X) -> X_transformed\n\n copy : boolean, optional\n ... |
Please provide a description of the function:def _matrix_adjust(self, X):
data_matrix = X.data if sparse.issparse(X) else X
# Shift all values to specially encode for NAN/infinity/OTHER and 0
# Old value New Value
# --------- ---------
# N (0..int_max)... | [
"Adjust all values in X to encode for NaNs and infinities in the data.\n\n Parameters\n ----------\n X : array-like, shape=(n_samples, n_feature)\n Input array of type int.\n\n Returns\n -------\n X : array-like, shape=(n_samples, n_feature)\n Input ar... |
Please provide a description of the function:def _fit_transform(self, X):
X = self._matrix_adjust(X)
X = check_array(
X,
accept_sparse='csc',
force_all_finite=False,
dtype=int
)
if X.min() < 0:
raise ValueError("X nee... | [
"Assume X contains only categorical features.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n Dense array or sparse matrix.\n "
] |
Please provide a description of the function:def fit_transform(self, X, y=None):
if self.categorical_features == "auto":
self.categorical_features = auto_select_categorical_features(X, threshold=self.threshold)
return _transform_selected(
X,
self._fit_transf... | [
"Fit OneHotEncoder to X, then transform X.\n\n Equivalent to self.fit(X).transform(X), but more convenient and more\n efficient. See fit for the parameters, transform for the return value.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)... |
Please provide a description of the function:def _transform(self, X):
X = self._matrix_adjust(X)
X = check_array(X, accept_sparse='csc', force_all_finite=False,
dtype=int)
if X.min() < 0:
raise ValueError("X needs to contain only non-negative integer... | [
"Asssume X contains only categorical features.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n Dense array or sparse matrix.\n "
] |
Please provide a description of the function:def transform(self, X):
return _transform_selected(
X, self._transform,
self.categorical_features,
copy=True
) | [
"Transform X using one-hot encoding.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n Dense array or sparse matrix.\n\n Returns\n -------\n X_out : sparse matrix if sparse=True else a 2-d array, dtype=int\n ... |
Please provide a description of the function:def fit(self, features, target, sample_weight=None, groups=None):
self._fit_init()
features, target = self._check_dataset(features, target, sample_weight)
self.pretest_X, _, self.pretest_y, _ = train_test_split(features,
... | [
"Fit an optimized machine learning pipeline.\n\n Uses genetic programming to optimize a machine learning pipeline that\n maximizes score on the provided features and target. Performs internal\n k-fold cross-validaton to avoid overfitting on the provided data. The\n best pipeline is then ... |
Please provide a description of the function:def _setup_memory(self):
if self.memory:
if isinstance(self.memory, str):
if self.memory == "auto":
# Create a temporary folder to store the transformers of the pipeline
self._cachedir = mkd... | [
"Setup Memory object for memory caching.\n "
] |
Please provide a description of the function:def _update_top_pipeline(self):
# 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._pareto_front.items, ... | [
"Helper function to update the _optimized_pipeline field."
] |
Please provide a description of the function:def _summary_of_best_pipeline(self, features, target):
if not self._optimized_pipeline:
raise RuntimeError('There was an error in the TPOT optimization '
'process. This could be because the data was '
... | [
"Print out best pipeline at the end of optimization process.\n\n Parameters\n ----------\n features: array-like {n_samples, n_features}\n Feature matrix\n\n target: array-like {n_samples}\n List of class labels for prediction\n\n Returns\n -------\n ... |
Please provide a description of the function:def predict(self, features):
if not self.fitted_pipeline_:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
features = self._check_dataset(features, target=None, sample_weight=None)
return se... | [
"Use the optimized pipeline to predict the target for a feature set.\n\n Parameters\n ----------\n features: array-like {n_samples, n_features}\n Feature matrix\n\n Returns\n ----------\n array-like: {n_samples}\n Predicted target for the samples in th... |
Please provide a description of the function:def fit_predict(self, features, target, sample_weight=None, groups=None):
self.fit(features, target, sample_weight=sample_weight, groups=groups)
return self.predict(features) | [
"Call fit and predict in sequence.\n\n Parameters\n ----------\n features: array-like {n_samples, n_features}\n Feature matrix\n target: array-like {n_samples}\n List of class labels for prediction\n sample_weight: array-like {n_samples}, optional\n ... |
Please provide a description of the function:def score(self, testing_features, testing_target):
if self.fitted_pipeline_ is None:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
testing_features, testing_target = self._check_dataset(testing_fea... | [
"Return the score on the given testing data using the user-specified scoring function.\n\n Parameters\n ----------\n testing_features: array-like {n_samples, n_features}\n Feature matrix of the testing set\n testing_target: array-like {n_samples}\n List of class lab... |
Please provide a description of the function:def predict_proba(self, features):
if not self.fitted_pipeline_:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
else:
if not (hasattr(self.fitted_pipeline_, 'predict_proba')):
... | [
"Use the optimized pipeline to estimate the class probabilities for a feature set.\n\n Parameters\n ----------\n features: array-like {n_samples, n_features}\n Feature matrix of the testing set\n\n Returns\n -------\n array-like: {n_samples, n_target}\n ... |
Please provide a description of the function:def clean_pipeline_string(self, individual):
dirty_string = str(individual)
# There are many parameter prefixes in the pipeline strings, used solely for
# making the terminal name unique, eg. LinearSVC__.
parameter_prefixes = [(m.star... | [
"Provide a string of the individual without the parameter prefixes.\n\n Parameters\n ----------\n individual: individual\n Individual which should be represented by a pretty string\n\n Returns\n -------\n A string like str(individual), but with parameter prefixes... |
Please provide a description of the function:def _check_periodic_pipeline(self, gen):
self._update_top_pipeline()
if self.periodic_checkpoint_folder is not None:
total_since_last_pipeline_save = (datetime.now() - self._last_pipeline_write).total_seconds()
if total_since_... | [
"If enough time has passed, save a new optimized pipeline. Currently used in the per generation hook in the optimization loop.\n Parameters\n ----------\n gen: int\n Generation number\n\n Returns\n -------\n None\n "
] |
Please provide a description of the function:def export(self, output_file_name, data_file_path=''):
if self._optimized_pipeline is None:
raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
to_write = export_pipeline(self._optimized_pipeline,
... | [
"Export the optimized pipeline as Python code.\n\n Parameters\n ----------\n output_file_name: string\n String containing the path and file name of the desired output file\n data_file_path: string (default: '')\n By default, the path of input dataset is 'PATH/TO/DAT... |
Please provide a description of the function:def _impute_values(self, features):
if self.verbosity > 1:
print('Imputing missing values in feature set')
if self._fitted_imputer is None:
self._fitted_imputer = Imputer(strategy="median")
self._fitted_imputer.fi... | [
"Impute missing values in a feature set.\n\n Parameters\n ----------\n features: array-like {n_samples, n_features}\n A feature matrix\n\n Returns\n -------\n array-like {n_samples, n_features}\n "
] |
Please provide a description of the function:def _check_dataset(self, features, target, sample_weight=None):
# Check sample_weight
if sample_weight is not None:
try: sample_weight = np.array(sample_weight).astype('float')
except ValueError as e:
raise Val... | [
"Check if a dataset has a valid feature set and labels.\n\n Parameters\n ----------\n features: array-like {n_samples, n_features}\n Feature matrix\n target: array-like {n_samples} or None\n List of class labels for prediction\n sample_weight: array-like {n_s... |
Please provide a description of the function:def _compile_to_sklearn(self, expr):
sklearn_pipeline_str = generate_pipeline_code(expr_to_tree(expr, self._pset), self.operators)
sklearn_pipeline = eval(sklearn_pipeline_str, self.operators_context)
sklearn_pipeline.memory = self._memory
... | [
"Compile a DEAP pipeline into a sklearn pipeline.\n\n Parameters\n ----------\n expr: DEAP individual\n The DEAP pipeline to be compiled\n\n Returns\n -------\n sklearn_pipeline: sklearn.pipeline.Pipeline\n "
] |
Please provide a description of the function:def _set_param_recursive(self, pipeline_steps, parameter, value):
for (_, obj) in pipeline_steps:
recursive_attrs = ['steps', 'transformer_list', 'estimators']
for attr in recursive_attrs:
if hasattr(obj, attr):
... | [
"Recursively iterate through all objects in the pipeline and set a given parameter.\n\n Parameters\n ----------\n pipeline_steps: array-like\n List of (str, obj) tuples from a scikit-learn pipeline or related object\n parameter: str\n The parameter to assign a value... |
Please provide a description of the function:def _stop_by_max_time_mins(self):
if self.max_time_mins:
total_mins_elapsed = (datetime.now() - self._start_datetime).total_seconds() / 60.
if total_mins_elapsed >= self.max_time_mins:
raise KeyboardInterrupt('{} minut... | [
"Stop optimization process once maximum minutes have elapsed."
] |
Please provide a description of the function:def _combine_individual_stats(self, operator_count, cv_score, individual_stats):
stats = deepcopy(individual_stats) # Deepcopy, since the string reference to predecessor should be cloned
stats['operator_count'] = operator_count
stats['intern... | [
"Combine the stats with operator count and cv score and preprare to be written to _evaluated_individuals\n\n Parameters\n ----------\n operator_count: int\n number of components in the pipeline\n cv_score: float\n internal cross validation score\n individual_... |
Please provide a description of the function:def _evaluate_individuals(self, population, features, target, sample_weight=None, groups=None):
# Evaluate the individuals with an invalid fitness
individuals = [ind for ind in population if not ind.fitness.valid]
# update pbar for valid ind... | [
"Determine the fit of the provided individuals.\n\n Parameters\n ----------\n population: a list of DEAP individual\n One individual is a list of pipeline operators and model parameters that can be\n compiled by DEAP into a callable function\n features: numpy.ndarra... |
Please provide a description of the function:def _preprocess_individuals(self, individuals):
# update self._pbar.total
if not (self.max_time_mins is None) and not self._pbar.disable and self._pbar.total <= self._pbar.n:
self._pbar.total += self._lambda
# Check we do not eval... | [
"Preprocess DEAP individuals before pipeline evaluation.\n\n Parameters\n ----------\n individuals: a list of DEAP individual\n One individual is a list of pipeline operators and model parameters that can be\n compiled by DEAP into a callable function\n\n Returns\n ... |
Please provide a description of the function:def _update_evaluated_individuals_(self, result_score_list, eval_individuals_str, operator_counts, stats_dicts):
for result_score, individual_str in zip(result_score_list, eval_individuals_str):
if type(result_score) in [float, np.float64, np.flo... | [
"Update self.evaluated_individuals_ and error message during pipeline evaluation.\n\n Parameters\n ----------\n result_score_list: list\n A list of CV scores for evaluated pipelines\n eval_individuals_str: list\n A list of strings for evaluated pipelines\n op... |
Please provide a description of the function:def _update_pbar(self, pbar_num=1, pbar_msg=None):
if not isinstance(self._pbar, type(None)):
if self.verbosity > 2 and pbar_msg is not None:
self._pbar.write(pbar_msg, file=self._file)
if not self._pbar.disable:
... | [
"Update self._pbar and error message during pipeline evaluation.\n\n Parameters\n ----------\n pbar_num: int\n How many pipelines has been processed\n pbar_msg: None or string\n Error message\n\n Returns\n -------\n None\n "
] |
Please provide a description of the function:def _random_mutation_operator(self, individual, allow_shrink=True):
if self.tree_structure:
mutation_techniques = [
partial(gp.mutInsert, pset=self._pset),
partial(mutNodeReplacement, pset=self._pset)
]... | [
"Perform a replacement, insertion, or shrink mutation on an individual.\n\n Parameters\n ----------\n individual: DEAP individual\n A list of pipeline operators and model parameters that can be\n compiled by DEAP into a callable function\n\n allow_shrink: bool (True... |
Please provide a description of the function:def _gen_grow_safe(self, pset, min_, max_, type_=None):
def condition(height, depth, type_):
return type_ not in self.ret_types or depth == height
return self._generate(pset, min_, max_, condition, type_) | [
"Generate an expression where each leaf might have a different depth between min_ and max_.\n\n Parameters\n ----------\n pset: PrimitiveSetTyped\n Primitive set from which primitives are selected.\n min_: int\n Minimum height of the produced trees.\n max_: i... |
Please provide a description of the function:def _operator_count(self, individual):
operator_count = 0
for i in range(len(individual)):
node = individual[i]
if type(node) is deap.gp.Primitive and node.name != 'CombineDFs':
operator_count += 1
retu... | [
"Count the number of pipeline operators as a measure of pipeline complexity.\n\n Parameters\n ----------\n individual: list\n A grown tree with leaves at possibly different depths\n dependending on the condition function.\n\n Returns\n -------\n operat... |
Please provide a description of the function:def _update_val(self, val, result_score_list):
self._update_pbar()
if val == 'Timeout':
self._update_pbar(pbar_msg=('Skipped pipeline #{0} due to time out. '
'Continuing to the next pipeline.'.forma... | [
"Update values in the list of result scores and self._pbar during pipeline evaluation.\n\n Parameters\n ----------\n val: float or \"Timeout\"\n CV scores\n result_score_list: list\n A list of CV scores\n\n Returns\n -------\n result_score_list:... |
Please provide a description of the function:def _generate(self, pset, min_, max_, condition, type_=None):
if type_ is None:
type_ = pset.ret
expr = []
height = np.random.randint(min_, max_)
stack = [(0, type_)]
while len(stack) != 0:
depth, type_... | [
"Generate a Tree as a list of lists.\n\n The tree is build from the root to the leaves, and it stop growing when\n the condition is fulfilled.\n\n Parameters\n ----------\n pset: PrimitiveSetTyped\n Primitive set from which primitives are selected.\n min_: int\n ... |
Please provide a description of the function:def transform(self, X):
selected = auto_select_categorical_features(X, threshold=self.threshold)
X_sel, _, n_selected, _ = _X_selected(X, selected)
if n_selected == 0:
# No features selected.
raise ValueError('No cate... | [
"Select categorical features and transform them using OneHotEncoder.\n\n Parameters\n ----------\n X: numpy ndarray, {n_samples, n_components}\n New data, where n_samples is the number of samples and n_components is the number of components.\n\n Returns\n -------\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.