Search is not available for this dataset
text
stringlengths
75
104k
def time_logger(name): """This logs the time usage of a code block""" start_time = time.time() yield end_time = time.time() total_time = end_time - start_time logging.info("%s; time: %ss", name, total_time)
def initialize_ray(): """Initializes ray based on environment variables and internal defaults.""" if threading.current_thread().name == "MainThread": plasma_directory = None object_store_memory = os.environ.get("MODIN_MEMORY", None) if os.environ.get("MODIN_OUT_OF_CORE", "False").title()...
def apply( self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs ): """Applies func to the object. See notes in Parent class about this method. Args: func: The function to apply. ...
def get_dummies( data, prefix=None, prefix_sep="_", dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None, ): """Convert categorical variable into indicator variables. Args: data (array-like, Series, or DataFrame): data to encode. prefix (strin...
def apply( self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs ): """Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to...
def shuffle(self, func, lengths, **kwargs): """Shuffle the order of the data in this axis based on the `lengths`. Extends `BaseFrameAxisPartition.shuffle`. Args: func: The function to apply before splitting. lengths: The list of partition lengths to split the result int...
def deploy_axis_func( cls, axis, func, num_splits, kwargs, maintain_partitioning, *partitions ): """Deploy a function along a full axis in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: ...
def deploy_func_between_two_axis_partitions( cls, axis, func, num_splits, len_of_left, kwargs, *partitions ): """Deploy a function along a full axis between two data sets in Ray. Args: axis: The axis to perform the function along. func: The function to perform. ...
def query(self, expr, **kwargs): """Query columns of the DataManager with a boolean expression. Args: expr: Boolean expression to query the columns with. Returns: DataManager containing the rows where the boolean expression is satisfied. """ d...
def to_pandas(self): """Converts Modin DataFrame to Pandas DataFrame. Returns: Pandas DataFrame of the DataManager. """ df = self.data.to_pandas(is_transposed=self._is_transposed) if df.empty: dtype_dict = { col_name: pandas.Serie...
def deploy_ray_axis_func(axis, func, num_splits, kwargs, *partitions): """Deploy a function along a full axis in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: The number of splits to return (see `split_result_of_axis_func...
def deploy_ray_func_between_two_axis_partitions( axis, func, num_splits, len_of_left, kwargs, *partitions ): """Deploy a function along a full axis between two data sets in Ray. Args: axis: The axis to perform the function along. func: The function to perform. num_splits: The number...
def apply(self, func, num_splits=None, other_axis_partition=None, **kwargs): """Applies func to the object in the plasma store. See notes in Parent class about this method. Args: func: The function to apply. num_splits: The number of times to split the result object. ...
def shuffle(self, func, num_splits=None, **kwargs): """Shuffle the order of the data in this axis based on the `func`. Extends `BaseFrameAxisPartition.shuffle`. :param func: :param num_splits: :param kwargs: :return: """ if num_splits is None: ...
def deploy_ray_func(func, partition, kwargs): """Deploy a function to a partition in Ray. Args: func: The function to apply. partition: The partition to apply the function to. kwargs: A dictionary of keyword arguments for the function. Returns: The result of the function. ...
def get(self): """Gets the object out of the plasma store. Returns: The object from the plasma store. """ if len(self.call_queue): return self.apply(lambda x: x).get() return ray.get(self.oid)
def apply(self, func, **kwargs): """Apply a function to the object stored in this partition. Note: It does not matter if func is callable or an ObjectID. Ray will handle it correctly either way. The keyword arguments are sent as a dictionary. Args: func: The...
def to_pandas(self): """Convert the object stored in this partition to a Pandas DataFrame. Returns: A Pandas DataFrame. """ dataframe = self.get().to_pandas() assert type(dataframe) is pandas.DataFrame or type(dataframe) is pandas.Series return dataframe
def put(cls, obj): """Put an object in the Plasma store and wrap it in this object. Args: obj: The object to be put. Returns: A `RayRemotePartition` object. """ return PyarrowOnRayFramePartition(ray.put(pyarrow.Table.from_pandas(obj)))
def isna(obj): """ Detect missing values for an array-like object. Args: obj: Object to check for null or missing values. Returns: bool or array-like of bool """ if isinstance(obj, BasePandasDataset): return obj.isna() else: return pandas.isna(obj)
def merge( left, right, how="inner", on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=("_x", "_y"), copy=True, indicator=False, validate=None, ): """Database style join, where common columns in "on" are merged. A...
def is_distributed(partition_column, lower_bound, upper_bound): """ Check if is possible distribute a query given that args Args: partition_column: column used to share the data between the workers lower_bound: the minimum value to be requested from the partition_column upper_bound: the...
def is_table(engine, sql): """ Check with the given sql arg is query or table Args: engine: SQLAlchemy connection engine sql: SQL query or table name Returns: True for table or False if not """ if engine.dialect.has_table(engine, sql): return True return False
def get_table_metadata(engine, table): """ Extract all useful infos from the given table Args: engine: SQLAlchemy connection engine table: table name Returns: Dictionary of infos """ metadata = MetaData() metadata.reflect(bind=engine, only=[table]) table_metadata = ...
def get_table_columns(metadata): """ Extract columns names and python typos from metadata Args: metadata: Table metadata Returns: dict with columns names and python types """ cols = OrderedDict() for col in metadata.c: name = str(col).rpartition(".")[2] cols[nam...
def check_query(query): """ Check query sanity Args: query: query string Returns: None """ q = query.lower() if "select " not in q: raise InvalidQuery("SELECT word not found in the query: {0}".format(query)) if " from " not in q: raise InvalidQuery("FROM wor...
def get_query_columns(engine, query): """ Extract columns names and python typos from query Args: engine: SQLAlchemy connection engine query: SQL query Returns: dict with columns names and python types """ con = engine.connect() result = con.execute(query).fetchone() ...
def check_partition_column(partition_column, cols): """ Check partition_column existence and type Args: partition_column: partition_column name cols: dict with columns names and python types Returns: None """ for k, v in cols.items(): if k == partition_column: ...
def get_query_info(sql, con, partition_column): """ Return a columns name list and the query string Args: sql: SQL query or table name con: database connection or url string partition_column: column used to share the data between the workers Returns: Columns name list and q...
def query_put_bounders(query, partition_column, start, end): """ Put bounders in the query Args: query: SQL query string partition_column: partition_column name start: lower_bound end: upper_bound Returns: Query with bounders """ where = " WHERE TMP_TABLE.{0...
def compute_index(self, axis, data_object, compute_diff=True): """Computes the index after a number of rows have been removed. Note: In order for this to be used properly, the indexes must not be changed before you compute this. Args: axis: The axis to extract the index...
def _prepare_method(self, pandas_func, **kwargs): """Prepares methods given various metadata. Args: pandas_func: The function to prepare. Returns Helper function which handles potential transpose. """ if self._is_transposed: def helper(df, in...
def numeric_columns(self, include_bool=True): """Returns the numeric columns of the Manager. Returns: List of index names. """ columns = [] for col, dtype in zip(self.columns, self.dtypes): if is_numeric_dtype(dtype) and ( include_bool or ...
def numeric_function_clean_dataframe(self, axis): """Preprocesses numeric functions to clean dataframe and pick numeric indices. Args: axis: '0' if columns and '1' if rows. Returns: Tuple with return value(if any), indices to apply func to & cleaned Manager. """...
def _join_index_objects(self, axis, other_index, how, sort=True): """Joins a pair of index objects (columns or rows) by a given strategy. Args: axis: The axis index object to join (0 for columns, 1 for index). other_index: The other_index to join on. how: The type of...
def join(self, other, **kwargs): """Joins a list or two objects together. Args: other: The other object(s) to join on. Returns: Joined objects. """ if not isinstance(other, list): other = [other] return self._join_list_of_managers(oth...
def concat(self, axis, other, **kwargs): """Concatenates two objects together. Args: axis: The axis index object to join (0 for columns, 1 for index). other: The other_index to concat with. Returns: Concatenated objects. """ return self._appe...
def copartition(self, axis, other, how_to_join, sort, force_repartition=False): """Copartition two QueryCompiler objects. Args: axis: The axis to copartition along. other: The other Query Compiler(s) to copartition against. how_to_join: How to manage joining the inde...
def to_pandas(self): """Converts Modin DataFrame to Pandas DataFrame. Returns: Pandas DataFrame of the DataManager. """ df = self.data.to_pandas(is_transposed=self._is_transposed) if df.empty: if len(self.columns) != 0: df = pandas.DataFra...
def from_pandas(cls, df, block_partitions_cls): """Improve simple Pandas DataFrame to an advanced and superior Modin DataFrame. Args: cls: DataManger object to convert the DataFrame to. df: Pandas DataFrame object. block_partitions_cls: BlockParitions object to store...
def _inter_manager_operations(self, other, how_to_join, func): """Inter-data operations (e.g. add, sub). Args: other: The other Manager for the operation. how_to_join: The type of join to join to make (e.g. right, outer). Returns: New DataManager with new da...
def _inter_df_op_handler(self, func, other, **kwargs): """Helper method for inter-manager and scalar operations. Args: func: The function to use on the Manager/scalar. other: The other Manager/scalar. Returns: New DataManager with new data and index. ...
def binary_op(self, op, other, **kwargs): """Perform an operation between two objects. Note: The list of operations is as follows: - add - eq - floordiv - ge - gt - le - lt - mod - mul ...
def update(self, other, **kwargs): """Uses other manager to update corresponding values in this manager. Args: other: The other manager. Returns: New DataManager with updated data and index. """ assert isinstance( other, type(self) ),...
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. Returns: New DataManager with updated data and index. """ assert isinstance( cond...
def _scalar_operations(self, axis, scalar, func): """Handler for mapping scalar operations across a Manager. Args: axis: The axis index object to execute the function on. scalar: The scalar value to map. func: The function to use on the Manager with the scalar. ...
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 conform 'axis' on to. Returns: A new QueryCompiler with updated data and new index. """ ...
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 index. """ drop = kwargs.get("drop", False) new_index = pandas.RangeIndex(len(self.index)) if not drop...
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.c...
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 rows. Default is 0. map_func: Callable function to map the dataframe. reduce_func: Callable function to reduc...
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 objects from each column or row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis",...
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 or row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 ...
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()....
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: Whether to ignore axis when raising TypeError Return: A new QueryCompiler object with sum or prod of th...
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 row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.t...
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 boolean. """ axis = kwargs.get("axis", 0) axis = 0 if axis is None else axis kwargs["axis"] = axis ...
def all(self, **kwargs): """Returns whether all the elements are true, potentially over an axis. Return: A new QueryCompiler object containing boolean values or boolean. """ if self._is_transposed: # Pandas ignores on axis=1 kwargs["bool_only"] = Fals...
def astype(self, col_dtypes, **kwargs): """Converts columns dtypes to given dtypes. Args: col_dtypes: Dictionary of {col: dtype,...} where col is the column name and dtype is a numpy dtype. Returns: DataFrame with updated dtypes. """ # Gr...
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: Function to reduce the Manager by. This function takes in a Manager. axis: axis to apply the function to. alter...
def first_valid_index(self): """Returns index of first non-NaN/NULL value. Return: Scalar of index name. """ # It may be possible to incrementally check each partition, but this # computation is fairly cheap. def first_valid_index_builder(df): df....
def idxmax(self, **kwargs): """Returns the first occurrence of the maximum over requested axis. Returns: A new QueryCompiler object containing the maximum of each column or axis. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 r...
def idxmin(self, **kwargs): """Returns the first occurrence of the minimum over requested axis. Returns: A new QueryCompiler object containing the minimum of each column or axis. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 r...
def last_valid_index(self): """Returns index of last non-NaN/NULL value. Return: Scalar of index name. """ def last_valid_index_builder(df): df.index = pandas.RangeIndex(len(df.index)) return df.apply(lambda df: df.last_valid_index()) func =...
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...
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...
def quantile_for_single_value(self, **kwargs): """Returns quantile of each column or row. Returns: A new QueryCompiler object containing the quantile of each column or row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return ...
def _full_axis_reduce_along_select_indices(self, func, axis, index): """Reduce Manger along select indices using function that needs full axis. Args: func: Callable that reduces the dimension of the object and requires full knowledge of the entire axis. axis: 0 f...
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) ...
def dropna(self, **kwargs): """Returns a new QueryCompiler with null values dropped along given axis. Return: a new DataManager """ axis = kwargs.get("axis", 0) subset = kwargs.get("subset", None) thresh = kwargs.get("thresh", None) how = kwargs.get("h...
def eval(self, expr, **kwargs): """Returns a new QueryCompiler with expr evaluated on columns. Args: expr: The string expression to evaluate. Returns: A new QueryCompiler with new columns after applying expr. """ columns = self.index if self._is_transpos...
def mode(self, **kwargs): """Returns a new QueryCompiler with modes calculated for each label along given axis. Returns: A new QueryCompiler with modes calculated. """ axis = kwargs.get("axis", 0) def mode_builder(df, **kwargs): result = df.mode(**kwargs...
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")...
def query(self, expr, **kwargs): """Query columns of the DataManager with a boolean expression. Args: expr: Boolean expression to query the columns with. Returns: DataManager containing the rows where the boolean expression is satisfied. """ columns = se...
def rank(self, **kwargs): """Computes numerical rank along axis. Equal values are set to the average. Returns: DataManager containing the ranks of the values along an axis. """ axis = kwargs.get("axis", 0) numeric_only = True if axis else kwargs.get("numeric_only", F...
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 or indices. """ axis = kwargs.pop("axis", 0) index = self.columns if axis else self.index # sort_i...
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 for columns and 1 for rows. func: Callable mapping function over the BlockParitions. indices: in...
def quantile_for_list_of_values(self, **kwargs): """Returns Manager containing quantiles along an axis for numeric columns. Returns: DataManager containing quantiles of original DataManager along an axis. """ if self._is_transposed: kwargs["axis"] = kwargs.get("a...
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 original DataManager. """ # See head for an explanation of the transposed behavior if ...
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 columns of the original DataManager. """ new_dtypes = ( self._dtype_cache if self._dt...
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_f...
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, inter...
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 column to. Returns: A new QueryCompiler """ def setitem(df, internal_indices=[])...
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. Returns: A new QueryCompiler. """ if self._is_transposed: return self.t...
def insert(self, loc, column, value): """Insert new column data. Args: loc: Insertion index. column: Column labels to insert. value: Dtype object values to insert. Returns: A new PandasQueryCompiler with new data inserted. """ if ...
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. Returns: A new PandasQueryCompiler. """ if callable(func): return sel...
def _post_process_apply(self, result_data, axis, try_scale=True): """Recompute the index after applying function. Args: result_data: a BaseFrameManager object. axis: Target axis along which function was applied. Returns: A new PandasQueryCompiler. ""...
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 to apply the function along. Returns: A new PandasQueryCompiler. """ if "axis" not...
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 apply the function along. Returns: A new PandasQueryCompiler. """ func_prepared = s...
def _callable_func(self, func, axis, *args, **kwargs): """Apply callable functions across given axis. Args: func: The functions to apply. axis: Target axis to apply the function along. Returns: A new PandasQueryCompiler. """ def callable_app...
def _manual_repartition(self, axis, repartition_func, **kwargs): """This method applies all manual partitioning functions. Args: axis: The axis to shuffle data along. repartition_func: The function used to repartition data. Returns: A `BaseFrameManager` obje...
def get_dummies(self, columns, **kwargs): """Convert categorical variables to dummy variables for certain columns. Args: columns: The columns to convert. Returns: A new QueryCompiler. """ cls = type(self) # `columns` as None does not mean all col...
def global_idx_to_numeric_idx(self, axis, indices): """ Note: this function involves making copies of the index in memory. Args: axis: Axis to extract indices. indices: Indices to convert to numerical. Returns: An Index object. """ as...
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 = sel...
def block_lengths(self): """Gets the lengths of the blocks. Note: This works with the property structure `_lengths_cache` to avoid having to recompute these values each time they are needed. """ if self._lengths_cache is None: # The first column will have the cor...
def block_widths(self): """Gets the widths of the blocks. Note: This works with the property structure `_widths_cache` to avoid having to recompute these values each time they are needed. """ if self._widths_cache is None: # The first column will have the correct...
def _update_inplace(self, new_query_compiler): """Updates the current DataFrame inplace. Args: new_query_compiler: The new QueryCompiler to use to manage the data """ old_query_compiler = self._query_compiler self._query_compiler = new_query_compiler ...
def _validate_other( self, other, axis, numeric_only=False, numeric_or_time_only=False, numeric_or_object_only=False, comparison_dtypes_only=False, ): """Helper method to check validity of other in inter-df operations""" axis = self._...
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 isins...
def abs(self): """Apply an absolute value function to all numeric columns. Returns: A new DataFrame with the applied absolute value. """ self._validate_dtypes(numeric_only=True) return self.__constructor__(query_compiler=self._query_compiler.abs())
def add(self, other, axis="columns", level=None, fill_value=None): """Add this DataFrame to another or a scalar/list. Args: other: What to add this this DataFrame. axis: The axis to apply addition over. Only applicaable to Series or list 'other'. ...