text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where(self, cond, other, **kwargs): """Gets values from this manager where cond is true else from other. Args: cond: Condition on which to evaluate values. R...
assert isinstance( cond, type(self) ), "Must have the same DataManager subclass to perform this operation" if isinstance(other, type(self)): # Note: Currently we are doing this with two maps across the entire # data. This can be done with a single map, but i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scalar_operations(self, axis, scalar, func): """Handler for mapping scalar operations across a Manager. Args: axis: The axis index object to execute the fun...
if isinstance(scalar, (list, np.ndarray, pandas.Series)): new_index = self.index if axis == 0 else self.columns def list_like_op(df): if axis == 0: df.index = new_index else: df.columns = new_index ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reindex(self, axis, labels, **kwargs): """Fits a new index for this Manger. Args: axis: The axis index object to target the reindex on. labels: New labels to...
# To reindex, we need a function that will be shipped to each of the # partitions. def reindex_builer(df, axis, old_labels, new_labels, **kwargs): if axis: while len(df.columns) < len(old_labels): df[len(df.columns)] = np.nan df.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_index(self, **kwargs): """Removes all levels from index and sets a default level_0 index. Returns: A new QueryCompiler with updated data and reset inde...
drop = kwargs.get("drop", False) new_index = pandas.RangeIndex(len(self.index)) if not drop: if isinstance(self.index, pandas.MultiIndex): # TODO (devin-petersohn) ensure partitioning is properly aligned new_column_names = pandas.Index(self.index.name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transpose(self, *args, **kwargs): """Transposes this DataManager. Returns: Transposed new DataManager. """
new_data = self.data.transpose(*args, **kwargs) # Switch the index and columns and transpose the new_manager = self.__constructor__(new_data, self.columns, self.index) # It is possible that this is already transposed new_manager._is_transposed = self._is_transposed ^ 1 r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _full_reduce(self, axis, map_func, reduce_func=None): """Apply function that will reduce the data to a Pandas Series. Args: axis: 0 for columns and 1 for row...
if reduce_func is None: reduce_func = map_func mapped_parts = self.data.map_across_blocks(map_func) full_frame = mapped_parts.map_across_full_axis(axis, reduce_func) if axis == 0: columns = self.columns return self.__constructor__( fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, **kwargs): """Counts the number of non-NaN objects for each column or row. Return: A new QueryCompiler object containing counts of non-NaN object...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().count(**kwargs) axis = kwargs.get("axis", 0) map_func = self._build_mapreduce_func(pandas.DataFrame.count, **kwargs) reduce_func = self._build_mapreduce_func(pandas.DataFra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mean(self, **kwargs): """Returns the mean for each numerical column or row. Return: A new QueryCompiler object containing the mean from each numerical column...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().mean(**kwargs) # Pandas default is 0 (though not mentioned in docs) axis = kwargs.get("axis", 0) sums = self.sum(**kwargs) counts = self.count(axis=axis, numeric_on...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def min(self, **kwargs): """Returns the minimum from each column or row. Return: A new QueryCompiler object with the minimum value from each column or row. """
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().min(**kwargs) mapreduce_func = self._build_mapreduce_func(pandas.DataFrame.min, **kwargs) return self._full_reduce(kwargs.get("axis", 0), mapreduce_func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_sum_prod(self, func, **kwargs): """Calculates the sum or product of the DataFrame. Args: func: Pandas func to apply to DataFrame. ignore_axis: Wheth...
axis = kwargs.get("axis", 0) min_count = kwargs.get("min_count", 0) def sum_prod_builder(df, **kwargs): return func(df, **kwargs) if min_count <= 1: return self._full_reduce(axis, sum_prod_builder) else: return self._full_axis_reduce(axis, s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prod(self, **kwargs): """Returns the product of each numerical column or row. Return: A new QueryCompiler object with the product of each numerical column or...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().prod(**kwargs) return self._process_sum_prod( self._build_mapreduce_func(pandas.DataFrame.prod, **kwargs), **kwargs )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_all_any(self, func, **kwargs): """Calculates if any or all the values are true. Return: A new QueryCompiler object containing boolean values or bool...
axis = kwargs.get("axis", 0) axis = 0 if axis is None else axis kwargs["axis"] = axis builder_func = self._build_mapreduce_func(func, **kwargs) return self._full_reduce(axis, builder_func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all(self, **kwargs): """Returns whether all the elements are true, potentially over an axis. Return: A new QueryCompiler object containing boolean values or ...
if self._is_transposed: # Pandas ignores on axis=1 kwargs["bool_only"] = False kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().all(**kwargs) return self._process_all_any(lambda df, **kwargs: df.all(**kwargs), **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def astype(self, col_dtypes, **kwargs): """Converts columns dtypes to given dtypes. Args: name and dtype is a numpy dtype. Returns: DataFrame with updated dtypes...
# Group indices to update by dtype for less map operations dtype_indices = {} columns = col_dtypes.keys() numeric_indices = list(self.columns.get_indexer_for(columns)) # Create Series for the updated dtypes new_dtypes = self.dtypes.copy() for i, column in enumera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _full_axis_reduce(self, axis, func, alternate_index=None): """Applies map that reduce Manager to series but require knowledge of full axis. Args: func: Funct...
result = self.data.map_across_full_axis(axis, func) if axis == 0: columns = alternate_index if alternate_index is not None else self.columns return self.__constructor__(result, index=["__reduced__"], columns=columns) else: index = alternate_index if alternate...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def idxmax(self, **kwargs): """Returns the first occurrence of the maximum over requested axis. Returns: A new QueryCompiler object containing the maximum of eac...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().idxmax(**kwargs) axis = kwargs.get("axis", 0) index = self.index if axis == 0 else self.columns def idxmax_builder(df, **kwargs): if axis == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def idxmin(self, **kwargs): """Returns the first occurrence of the minimum over requested axis. Returns: A new QueryCompiler object containing the minimum of eac...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().idxmin(**kwargs) axis = kwargs.get("axis", 0) index = self.index if axis == 0 else self.columns def idxmin_builder(df, **kwargs): if axis == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median(self, **kwargs): """Returns median of each column or row. Returns: A new QueryCompiler object containing the median of each column or row. """
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().median(**kwargs) # Pandas default is 0 (though not mentioned in docs) axis = kwargs.get("axis", 0) func = self._build_mapreduce_func(pandas.DataFrame.median, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memory_usage(self, **kwargs): """Returns the memory usage of each column. Returns: A new QueryCompiler object containing the memory usage of each column. """
def memory_usage_builder(df, **kwargs): return df.memory_usage(**kwargs) func = self._build_mapreduce_func(memory_usage_builder, **kwargs) return self._full_axis_reduce(0, func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quantile_for_single_value(self, **kwargs): """Returns quantile of each column or row. Returns: A new QueryCompiler object containing the quantile of each col...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().quantile_for_single_value(**kwargs) axis = kwargs.get("axis", 0) q = kwargs.get("q", 0.5) assert type(q) is float def quantile_builder(df, **kwargs): t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _full_axis_reduce_along_select_indices(self, func, axis, index): """Reduce Manger along select indices using function that needs full axis. Args: func: Calla...
# Convert indices to numeric indices old_index = self.index if axis else self.columns numeric_indices = [i for i, name in enumerate(old_index) if name in index] result = self.data.apply_func_to_select_indices_along_full_axis( axis, func, numeric_indices ) ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe(self, **kwargs): """Generates descriptive statistics. Returns: DataFrame object containing the descriptive statistics of the DataFrame. """
# Use pandas to calculate the correct columns new_columns = ( pandas.DataFrame(columns=self.columns) .astype(self.dtypes) .describe(**kwargs) .columns ) def describe_builder(df, internal_indices=[], **kwargs): return df.iloc[:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval(self, expr, **kwargs): """Returns a new QueryCompiler with expr evaluated on columns. Args: expr: The string expression to evaluate. Returns: A new Quer...
columns = self.index if self._is_transposed else self.columns index = self.columns if self._is_transposed else self.index # Make a copy of columns and eval on the copy to determine if result type is # series or not columns_copy = pandas.DataFrame(columns=self.columns) c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mode(self, **kwargs): """Returns a new QueryCompiler with modes calculated for each label along given axis. Returns: A new QueryCompiler with modes calculate...
axis = kwargs.get("axis", 0) def mode_builder(df, **kwargs): result = df.mode(**kwargs) # We return a dataframe with the same shape as the input to ensure # that all the partitions will be the same shape if not axis and len(df) != len(result): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fillna(self, **kwargs): """Replaces NaN values with the method provided. Returns: A new QueryCompiler with null values filled. """
axis = kwargs.get("axis", 0) value = kwargs.get("value") if isinstance(value, dict): value = kwargs.pop("value") if axis == 0: index = self.columns else: index = self.index value = { idx: value[key]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, expr, **kwargs): """Query columns of the DataManager with a boolean expression. Args: expr: Boolean expression to query the columns with. Returns...
columns = self.columns def query_builder(df, **kwargs): # This is required because of an Arrow limitation # TODO revisit for Arrow error df = df.copy() df.index = pandas.RangeIndex(len(df)) df.columns = columns df.query(expr, inpl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank(self, **kwargs): """Computes numerical rank along axis. Equal values are set to the average. Returns: DataManager containing the ranks of the values alo...
axis = kwargs.get("axis", 0) numeric_only = True if axis else kwargs.get("numeric_only", False) func = self._prepare_method(pandas.DataFrame.rank, **kwargs) new_data = self._map_across_full_axis(axis, func) # Since we assume no knowledge of internal state, we get the columns ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_index(self, **kwargs): """Sorts the data with respect to either the columns or the indices. Returns: DataManager containing the data sorted by columns o...
axis = kwargs.pop("axis", 0) index = self.columns if axis else self.index # sort_index can have ascending be None and behaves as if it is False. # sort_values cannot have ascending be None. Thus, the following logic is to # convert the ascending argument to one that works with ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _map_across_full_axis_select_indices( self, axis, func, indices, keep_remaining=False ): """Maps function to select indices along full axis. Args: axis: 0 fo...
return self.data.apply_func_to_select_indices_along_full_axis( axis, func, indices, keep_remaining )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quantile_for_list_of_values(self, **kwargs): """Returns Manager containing quantiles along an axis for numeric columns. Returns: DataManager containing quant...
if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().quantile_for_list_of_values(**kwargs) axis = kwargs.get("axis", 0) q = kwargs.get("q") numeric_only = kwargs.get("numeric_only", True) assert isinstance(q, (pandas....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tail(self, n): """Returns the last n rows. Args: n: Integer containing the number of rows to return. Returns: DataManager containing the last n rows of the o...
# See head for an explanation of the transposed behavior if n < 0: n = max(0, len(self.index) + n) if self._is_transposed: result = self.__constructor__( self.data.transpose().take(1, -n).transpose(), self.index[-n:], self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def front(self, n): """Returns the first n columns. Args: n: Integer containing the number of columns to return. Returns: DataManager containing the first n colu...
new_dtypes = ( self._dtype_cache if self._dtype_cache is None else self._dtype_cache[:n] ) # See head for an explanation of the transposed behavior if self._is_transposed: result = self.__constructor__( self.data.transpose().take(0, n).transpose()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getitem_column_array(self, key): """Get column data for target labels. Args: key: Target labels by which to retrieve data. Returns: A new QueryCompiler. """
# Convert to list for type checking numeric_indices = list(self.columns.get_indexer_for(key)) # Internal indices is left blank and the internal # `apply_func_to_select_indices` will do the conversion and pass it in. def getitem(df, internal_indices=[]): return df.il...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getitem_row_array(self, key): """Get row data for target labels. Args: key: Target numeric indices by which to retrieve data. Returns: A new QueryCompiler. "...
# Convert to list for type checking key = list(key) def getitem(df, internal_indices=[]): return df.iloc[internal_indices] result = self.data.apply_func_to_select_indices( 1, getitem, key, keep_remaining=False ) # We can't just set the index to ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setitem(self, axis, key, value): """Set the column defined by `key` to the `value` provided. Args: key: The column name to set. value: The value to set the c...
def setitem(df, internal_indices=[]): def _setitem(): if len(internal_indices) == 1: if axis == 0: df[df.columns[internal_indices[0]]] = value else: df.iloc[internal_indices[0]] = value ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drop(self, index=None, columns=None): """Remove row data for target index and columns. Args: index: Target index to drop. columns: Target columns to drop. Re...
if self._is_transposed: return self.transpose().drop(index=columns, columns=index).transpose() if index is None: new_data = self.data new_index = self.index else: def delitem(df, internal_indices=[]): return df.drop(index=df.index...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, loc, column, value): """Insert new column data. Args: loc: Insertion index. column: Column labels to insert. value: Dtype object values to inser...
if is_list_like(value): # TODO make work with another querycompiler object as `value`. # This will require aligning the indices with a `reindex` and ensuring that # the data is partitioned identically. if isinstance(value, pandas.Series): value = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply(self, func, axis, *args, **kwargs): """Apply func across given axis. Args: func: The function to apply. axis: Target axis to apply the function along. ...
if callable(func): return self._callable_func(func, axis, *args, **kwargs) elif isinstance(func, dict): return self._dict_func(func, axis, *args, **kwargs) elif is_list_like(func): return self._list_like_func(func, axis, *args, **kwargs) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _post_process_apply(self, result_data, axis, try_scale=True): """Recompute the index after applying function. Args: result_data: a BaseFrameManager object. a...
if try_scale: try: internal_index = self.compute_index(0, result_data, True) except IndexError: internal_index = self.compute_index(0, result_data, False) try: internal_columns = self.compute_index(1, result_data, True) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _dict_func(self, func, axis, *args, **kwargs): """Apply function to certain indices across given axis. Args: func: The function to apply. axis: Target axis t...
if "axis" not in kwargs: kwargs["axis"] = axis if axis == 0: index = self.columns else: index = self.index func = {idx: func[key] for key in func for idx in index.get_indexer_for([key])} def dict_apply_builder(df, func_dict={}): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list_like_func(self, func, axis, *args, **kwargs): """Apply list-like function across given axis. Args: func: The function to apply. axis: Target axis to ap...
func_prepared = self._prepare_method( lambda df: pandas.DataFrame(df.apply(func, axis, *args, **kwargs)) ) new_data = self._map_across_full_axis(axis, func_prepared) # When the function is list-like, the function names become the index/columns new_index = ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _callable_func(self, func, axis, *args, **kwargs): """Apply callable functions across given axis. Args: func: The functions to apply. axis: Target axis to ap...
def callable_apply_builder(df, axis=0): if not axis: df.index = index df.columns = pandas.RangeIndex(len(df.columns)) else: df.columns = index df.index = pandas.RangeIndex(len(df.index)) result = df.apply(func,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _manual_repartition(self, axis, repartition_func, **kwargs): """This method applies all manual partitioning functions. Args: axis: The axis to shuffle data a...
func = self._prepare_method(repartition_func, **kwargs) return self.data.manual_shuffle(axis, func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dummies(self, columns, **kwargs): """Convert categorical variables to dummy variables for certain columns. Args: columns: The columns to convert. Returns...
cls = type(self) # `columns` as None does not mean all columns, by default it means only # non-numeric columns. if columns is None: columns = [c for c in self.columns if not is_numeric_dtype(self.dtypes[c])] # If we aren't computing any dummies, there is no need ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_data(self) -> BaseFrameManager: """Perform the map step Returns: A BaseFrameManager object. """
def iloc(partition, row_internal_indices, col_internal_indices): return partition.iloc[row_internal_indices, col_internal_indices] masked_data = self.parent_data.apply_func_to_indices_both_axis( func=iloc, row_indices=self.index_map.values, col_indices=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_other( self, other, axis, numeric_only=False, numeric_or_time_only=False, numeric_or_object_only=False, comparison_dtypes_only=False, ): "...
axis = self._get_axis_number(axis) if axis is not None else 1 result = other if isinstance(other, BasePandasDataset): return other._query_compiler elif is_list_like(other): if axis == 0: if len(other) != len(self._query_compiler.index): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _default_to_pandas(self, op, *args, **kwargs): """Helper method to use default pandas function"""
empty_self_str = "" if not self.empty else " for empty DataFrame" ErrorMessage.default_to_pandas( "`{}.{}`{}".format( self.__name__, op if isinstance(op, str) else op.__name__, empty_self_str, ) ) if callab...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bool(self): """Return the bool of a single element PandasObject. This must be a boolean scalar value, either True or False. Raise a ValueError if the Pa...
shape = self.shape if shape != (1,) and shape != (1, 1): raise ValueError( """The PandasObject does not have exactly 1 element. Return the bool of a single element PandasObject. The truth value is ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 `p...
if self.call_queue: return self.apply(lambda df: df).data else: return self.data.copy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
import dask self.delayed_call = dask.delayed(func)(self.delayed_call, **kwargs) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 (BaseFramePart...
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) # TODO Not use pandas.DataFrame here, but something more general. _NAN_BLOCKS[shape] = partition_class.put(pandas.DataF...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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:...
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: return [result.iloc[sums[i] : sums[i + 1]] for i in range(len(sums) - 1)] else: return [result.iloc[:, sums[i] : sum...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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])...
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: row_loc = tup ndim = _compute_ndim(row_loc, col_loc) row_scaler...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_enlargement(locator, global_index): """Determine if a locator will enlarge the global index. Enlargement happens when you trying to locate using labels i...
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_index) ): n_diff_elems = len(pandas.Index(locator).difference(global_index)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# 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.DataFrame, DataFrame)): if not all(idx in item.index for idx in row_lookup): raise ValueError(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_items(self, row_lookup, col_lookup, item): """Perform remote write and replace blocks. """
self.qc.write_items(row_lookup, col_lookup, item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_enlarge_labels(self, locator, base_index): """Helper for _enlarge_axis, compute common labels and extra labels. Returns: nan_labels: The labels need...
# 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 = base_index_type(locator) nan_labels = locator_as_index.difference(base_index) common_label...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: ax...
splits = split_result_of_axis_func_pandas(axis, num_splits, df) if not isinstance(splits, list): splits = [splits] return splits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Ra...
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_result_for_readers(0, num_splits, df) + [len(df.index)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Pa...
index_col = kwargs.get("index_col", None) bio = file_open(fname, "rb") bio.seek(start) to_read = header + bio.read(end - start) bio.close() pandas_df = pandas.read_csv(BytesIO(to_read), **kwargs) pandas_df.columns = pandas.RangeIndex(len(pandas_df.columns)) if index_col is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Ra...
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) + [len(df.index)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 functi...
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_splits, df) + [len(df.index)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
index = partition_indices[0].append(partition_indices[1:]) index.names = index_name return index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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: ErrorMessage.default_to_pandas( "File format seems to be `fixed`. For better dist...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. ...
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: from pyarrow.feather import FeatherReader fr = FeatherReader(path) columns =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if not isinstance(arg, DataFrame): return pandas.to_datetime( arg, errors=errors, dayfirst=dayfirst, yearfirst=yearfirst, utc=utc, box=box, format=format, exact=exact, unit=unit, infer_da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copartition_datasets(self, axis, other, left_func, right_func): """Copartition two BlockPartitions objects. Args: axis: The axis to copartition. other: The o...
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 absolutely necessary. If we do need to # shuffle, we use the identity function and then reshuffle. if right_func i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 dimen...
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) ) else: return self.__constructor__( np.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# 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 # concatenated them, but the code is much smaller. if is_transposed: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 o...
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 extract the indices # Note: We use _partitions_cache in the context of this function to make # s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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.digitize(index, cumulative_column_widths)) if block_idx == len(cumulative_column_widths): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_c...
# 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(axis, i) for i in indices ] # In ordered, we have to maintain the order of the list of indices provided....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
preprocessed_func = self.preprocess_func(func) return [obj.apply(preprocessed_func, **kwargs) for obj in partitions]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False): """Applies a function to select indices. Note: Your internal function must tak...
if self.partitions.size == 0: return np.array([[]]) # Handling dictionaries has to be done differently, but we still want # to figure out the partitions that need to be applied to, so we will # store the dictionary in a separate variable and assign `indices` to # the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if keep_remaining: row_partitions_list = self._get_dict_of_block_index(1, row_indices).items() col_partitions_list = self._get_dict_of_block_index(0, col_indices).items() else: row_partitions_list = self._get_dict_of_block_index( 1, row_indices, order...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inter_data_operation(self, axis, func, other): """Apply a function that requires two BaseFrameManager objects. Args: axis: The axis to apply the function ove...
if axis: partitions = self.row_partitions other_partitions = other.row_partitions else: partitions = self.column_partitions other_partitions = other.column_partitions func = self.preprocess_func(func) result = np.array( [ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manual_shuffle(self, axis, shuffle_func, lengths): """Shuffle the partitions based on the `shuffle_func`. Args: axis: The axis to shuffle across. shuffle_fun...
if axis: partitions = self.row_partitions else: partitions = self.column_partitions func = self.preprocess_func(shuffle_func) result = np.array([part.shuffle(func, lengths) for part in partitions]) return self.__constructor__(result) if axis else self.__c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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", names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 consider...
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.data[indptr_start:indptr_end]) else: unique = np.unique(X[:, column]) featur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]] X_not_sel = X[:, ind[non_sel]] return X_sel, X_not_sel, n_selected, n_features
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transform_selected(X, transform, selected, copy=True): """Apply a transform function to portion of selected features. Parameters X : array-like or sparse ma...
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_features = _X_selected(X, selected) if n_selected == 0: # No features selected. return X e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) Inp...
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) N + 3 # np.NaN 2 # infinity 2 # *o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. ...
if self.categorical_features == "auto": self.categorical_features = auto_select_categorical_features(X, threshold=self.threshold) return _transform_selected( X, self._fit_transform, self.categorical_features, copy=True )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ma...
return _transform_selected( X, self._transform, self.categorical_features, copy=True )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._cachedir = mkdtemp() else: if not os.path.isdir(self.mem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._pareto_front.items, reversed(self._pareto_front.keys)): if pipeline_scores.wvalues[1] > s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _summary_of_best_pipeline(self, features, target): """Print out best pipeline at the end of optimization process. Parameters features: array-like {n_samples,...
if not self._optimized_pipeline: raise RuntimeError('There was an error in the TPOT optimization ' 'process. This could be because the data was ' 'not formatted properly, or because data for ' 'a regression...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, features): """Use the optimized pipeline to predict the target for a feature set. Parameters features: array-like {n_samples, n_features} Featu...
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 self.fitted_pipeline_.predict(features)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit_predict(self, features, target, sample_weight=None, groups=None): """Call fit and predict in sequence. Parameters features: array-like {n_samples, n_feat...
self.fit(features, target, sample_weight=sample_weight, groups=groups) return self.predict(features)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score(self, testing_features, testing_target): """Return the score on the given testing data using the user-specified scoring function. Parameters testing_fe...
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_features, testing_target, sample_weight=None) # If the scoring function is a string, we must adjus...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict_proba(self, features): """Use the optimized pipeline to estimate the class probabilities for a feature set. Parameters features: array-like {n_sample...
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')): raise RuntimeError('The fitted pipeline does not have the predict_proba() function....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_pipeline_string(self, individual): """Provide a string of the individual without the parameter prefixes. Parameters individual: individual Individual w...
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.start(), m.end()) for m in re.finditer(', [\w]+__', dirty_string)] # We handle them in reverse...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export(self, output_file_name, data_file_path=''): """Export the optimized pipeline as Python code. Parameters output_file_name: string String containing the...
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, self.operators, self._pset, self._imputed,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _impute_values(self, features): """Impute missing values in a feature set. Parameters features: array-like {n_samples, n_features} A feature matrix Returns -...
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.fit(features) return self._fitted_imputer.transform(features)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_dataset(self, features, target, sample_weight=None): """Check if a dataset has a valid feature set and labels. Parameters features: array-like {n_samp...
# Check sample_weight if sample_weight is not None: try: sample_weight = np.array(sample_weight).astype('float') except ValueError as e: raise ValueError('sample_weight could not be converted to float array: %s' % e) if np.any(np.isnan(sample_weight))...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compile_to_sklearn(self, expr): """Compile a DEAP pipeline into a sklearn pipeline. Parameters expr: DEAP individual The DEAP pipeline to be compiled Return...
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 return sklearn_pipeline
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_param_recursive(self, pipeline_steps, parameter, value): """Recursively iterate through all objects in the pipeline and set a given parameter. Parameter...
for (_, obj) in pipeline_steps: recursive_attrs = ['steps', 'transformer_list', 'estimators'] for attr in recursive_attrs: if hasattr(obj, attr): self._set_param_recursive(getattr(obj, attr), parameter, value) if hasattr(obj, 'estimator'):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stop_by_max_time_mins(self): """Stop optimization process once maximum minutes have elapsed."""
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('{} minutes have elapsed. TPOT will close down.'.format(total_mins_elapsed))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _combine_individual_stats(self, operator_count, cv_score, individual_stats): """Combine the stats with operator count and cv score and preprare to be written...
stats = deepcopy(individual_stats) # Deepcopy, since the string reference to predecessor should be cloned stats['operator_count'] = operator_count stats['internal_cv_score'] = cv_score return stats