DataFrame ========= .. currentmodule:: pandasCore .. class:: DataFrame Two-dimensional labeled data structure with columns of potentially different types. Example ------- .. code-block:: python import pandasCore as pd # Create DataFrame from dict df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) print(df.shape) # (3, 2) print(df.columns) # ['A', 'B'] Attributes ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Attribute - Description - Example * - :attr:`~DataFrame.T` - The transpose of the DataFrame - :ref:`View ` * - :attr:`~DataFrame.columns` - The column labels of the DataFrame - :ref:`View ` * - :attr:`~DataFrame.empty` - Indicator whether DataFrame is empty - :ref:`View ` * - :attr:`~DataFrame.ncols` - Number of columns in the DataFrame - :ref:`View ` * - :attr:`~DataFrame.nrows` - Number of rows in the DataFrame - :ref:`View ` * - :attr:`~DataFrame.plot` - Return a PlotAccessor. Not implemented. - * - :attr:`~DataFrame.shape` - Return a tuple representing the dimensionality of the DataFrame - :ref:`View ` * - :attr:`~DataFrame.size` - Return an int representing the number of elements in this object - * - :attr:`~DataFrame.sparse` - Accessor for sparse data operations - :ref:`View ` * - :attr:`~DataFrame.style` - Return a Styler object. Not implemented. - Construction ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.__init__` ``(data: object = None, index: object = None, columns: object = None, dtype: object = None, copy: object = None)`` - Two-dimensional labeled data structure. - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.__getitem__` ``(*args, **kwargs) | (key: str) | (key: list)`` - Get column by name - * - :meth:`~DataFrame.__setitem__` ``(key: str, value: list)`` - Set column values. - * - :meth:`~DataFrame.first` ``(offset: str)`` - Select initial periods of time series data based on a date offset. - :ref:`View ` * - :meth:`~DataFrame.get` ``(key: str, default: object = None)`` - Get item from object for given key (column name). - :ref:`View ` * - :meth:`~DataFrame.head` ``(n: typing.SupportsInt = 5)`` - Return the first n rows. - :ref:`View ` * - :meth:`~DataFrame.idxmax` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False)`` - Return index of first occurrence of maximum over requested axis. - :ref:`View ` * - :meth:`~DataFrame.idxmin` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False)`` - Return index of first occurrence of minimum over requested axis. - :ref:`View ` * - :meth:`~DataFrame.last` ``(offset: str)`` - Select final periods of time series data based on a date offset. - :ref:`View ` * - :meth:`~DataFrame.mask` ``(cond: pandasCore.DataFrame, other: object = None, *, inplace: bool = False, axis: object = None, level: object = None)`` - Replace values where the condition is True. - * - :meth:`~DataFrame.nlargest` ``(n: typing.SupportsInt, columns: str, keep: str = 'first')`` - Return the first n rows ordered by columns in descending order. - :ref:`View ` * - :meth:`~DataFrame.nsmallest` ``(n: typing.SupportsInt, columns: str, keep: str = 'first')`` - Return the first n rows ordered by columns in ascending order. - :ref:`View ` * - :meth:`~DataFrame.query` ``(expr: str, *, inplace: bool = False, **kwargs)`` - Query the columns of a DataFrame with a boolean expression. - :ref:`View ` * - :meth:`~DataFrame.sample` ``(n: object = None, frac: object = None, replace: bool = False, weights: object = None, random_state: object = None, axis: object = None, ignore_index: bool = False)`` - Return a random sample of items from an axis of object. - :ref:`View ` * - :meth:`~DataFrame.tail` ``(n: typing.SupportsInt = 5)`` - Return the last n rows. - :ref:`View ` * - :meth:`~DataFrame.take` ``(indices: collections.abc.Sequence[typing.SupportsInt], axis: typing.SupportsInt = 0, **kwargs)`` - Return the elements in the given positional indices. - :ref:`View ` * - :meth:`~DataFrame.where` ``(cond: pandasCore.DataFrame, other: typing.SupportsFloat = nan, *, inplace: bool = False, axis: object = None, level: object = None)`` - Replace values where the condition is False. - :ref:`View ` * - :meth:`~DataFrame.xs` ``(key: str, axis: typing.SupportsInt = 0, level: object = None, drop_level: bool = True)`` - Return cross-section from the Series/DataFrame. - :ref:`View ` Data Manipulation ----------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.assign` ``(**kwargs)`` - Assign new columns to a DataFrame. - :ref:`View ` * - :meth:`~DataFrame.drop` ``(labels: object = None, *, axis: typing.SupportsInt = 0, index: object = None, columns: object = None, level: object = None, inplace: bool = False, errors: str = 'raise')`` - Drop specified labels from rows or columns. - :ref:`View ` * - :meth:`~DataFrame.droplevel` ``(level: object, axis: typing.SupportsInt = 0)`` - Return DataFrame with requested index / column level(s) removed. - :ref:`View ` * - :meth:`~DataFrame.insert` ``(loc: typing.SupportsInt, column: str, value: collections.abc.Sequence[typing.SupportsFloat], allow_duplicates: object = None)`` - Insert column into DataFrame at specified location. - :ref:`View ` * - :meth:`~DataFrame.pop` ``(item: str)`` - Return item and drop from frame. - :ref:`View ` * - :meth:`~DataFrame.reindex` ``(labels: object = None, *, index: object = None, columns: object = None, axis: object = None, method: object = None, copy: object = None, level: object = None, fill_value: object = nan, limit: object = None, tolerance: object = None)`` - Conform DataFrame to new index with optional filling logic. - :ref:`View ` * - :meth:`~DataFrame.rename` ``(mapper: object = None, *, index: object = None, columns: object = None, axis: object = None, copy: object = None, inplace: bool = False, level: object = None, errors: str = 'ignore')`` - Rename columns or index labels. - :ref:`View ` * - :meth:`~DataFrame.rename_axis` ``(mapper: object = None, *, index: object = None, columns: object = None, axis: typing.SupportsInt = 0, copy: object = None, inplace: bool = False)`` - Set the name of the axis for the index or columns. - :ref:`View ` * - :meth:`~DataFrame.reorder_levels` ``(order: collections.abc.Sequence[typing.SupportsInt], axis: typing.SupportsInt = 0)`` - Rearrange index levels using input order. - :ref:`View ` * - :meth:`~DataFrame.replace` ``(to_replace: object = None, value: object = None, *, inplace: bool = False, limit: object = None, regex: bool = False, method: object = None)`` - Replace values given in to_replace with value. - :ref:`View ` * - :meth:`~DataFrame.reset_index` ``(level: object = None, *, drop: bool = False, inplace: bool = False, col_level: object = 0, col_fill: object = '', allow_duplicates: object = None, names: object = None)`` - Reset the index, or a level of it. - * - :meth:`~DataFrame.set_axis` ``(labels: list, *, axis: typing.SupportsInt = 0, copy: object = None)`` - Assign desired index to given axis. - :ref:`View ` * - :meth:`~DataFrame.set_index` ``(*args, **kwargs) | (keys: object, *, drop: bool = True, append: bool = False, inplace: bool = False, verify_integrity: bool = False)`` - Set the DataFrame index using an existing column. - :ref:`View ` * - :meth:`~DataFrame.swaplevel` ``(i: typing.SupportsInt = -2, j: typing.SupportsInt = -1, axis: typing.SupportsInt = 0)`` - Swap levels i and j in a MultiIndex. - :ref:`View ` * - :meth:`~DataFrame.update` ``(other: pandasCore.DataFrame, join: str = 'left', overwrite: bool = True, filter_func: object = None, errors: str = 'ignore')`` - Modify in place using non-NA values from another DataFrame. - :ref:`View ` Missing Data ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.backfill` ``(*, axis: object = None, inplace: bool = False, limit: object = None, downcast: object = None)`` - Fill NA/NaN values using next valid observation. - :ref:`View ` * - :meth:`~DataFrame.bfill` ``(*, axis: object = None, inplace: bool = False, limit: object = None, limit_area: object = None, downcast: object = None)`` - Fill NA/NaN values by using the next valid observation to fill gap. - :ref:`View ` * - :meth:`~DataFrame.dropna` ``(*, axis: typing.SupportsInt = 0, how: object = None, thresh: object = None, subset: object = None, inplace: bool = False, ignore_index: bool = False)`` - Remove missing values. - :ref:`View ` * - :meth:`~DataFrame.ffill` ``(*, axis: object = None, inplace: bool = False, limit: object = None, limit_area: object = None, downcast: object = None)`` - Fill NA/NaN values by propagating the last valid observation forward. - :ref:`View ` * - :meth:`~DataFrame.fillna` ``(value: object = None, *, method: object = None, axis: object = None, inplace: bool = False, limit: object = None, downcast: object = None)`` - Fill NA/NaN values using the specified method. - :ref:`View ` * - :meth:`~DataFrame.interpolate` ``(method: str = 'linear', *, axis: object = 0, limit: object = None, inplace: bool = False, limit_direction: object = None, limit_area: object = None, downcast: object = None, **kwargs)`` - Fill NaN values using an interpolation method. - :ref:`View ` * - :meth:`~DataFrame.isna` ``()`` - Detect missing values. - :ref:`View ` * - :meth:`~DataFrame.isnull` ``()`` - Detect missing values (alias for isna). - :ref:`View ` * - :meth:`~DataFrame.notna` ``()`` - Detect non-missing values. - :ref:`View ` * - :meth:`~DataFrame.notnull` ``()`` - Detect non-missing values (alias for notna). - :ref:`View ` * - :meth:`~DataFrame.pad` ``(*, axis: object = None, inplace: bool = False, limit: object = None, downcast: object = None)`` - Fill NA/NaN values using previous valid observation. - :ref:`View ` Statistics ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.count` ``(axis: typing.SupportsInt = 0, numeric_only: bool = False)`` - Count non-NA cells for each column or row. - :ref:`View ` * - :meth:`~DataFrame.cummax` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative maximum over a DataFrame axis. - :ref:`View ` * - :meth:`~DataFrame.cummin` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative minimum over a DataFrame axis. - :ref:`View ` * - :meth:`~DataFrame.cumprod` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative product over a DataFrame axis. - :ref:`View ` * - :meth:`~DataFrame.cumsum` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative sum over a DataFrame axis. - :ref:`View ` * - :meth:`~DataFrame.describe` ``(percentiles: object = None, include: object = None, exclude: object = None)`` - Generate descriptive statistics. - :ref:`View ` * - :meth:`~DataFrame.kurt` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return unbiased kurtosis over requested axis. - :ref:`View ` * - :meth:`~DataFrame.kurtosis` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Alias for kurt() - :ref:`View ` * - :meth:`~DataFrame.max` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the maximum of the values over the requested axis. - :ref:`View ` * - :meth:`~DataFrame.mean` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the mean of the values over the requested axis. - :ref:`View ` * - :meth:`~DataFrame.median` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the median of the values over the requested axis. - :ref:`View ` * - :meth:`~DataFrame.min` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the minimum of the values over the requested axis. - :ref:`View ` * - :meth:`~DataFrame.mode` ``(axis: typing.SupportsInt = 0, numeric_only: bool = False, dropna: bool = True)`` - Get the mode(s) of each element along the selected axis. - :ref:`View ` * - :meth:`~DataFrame.nunique` ``(axis: typing.SupportsInt = 0, dropna: bool = True)`` - Count number of distinct elements in specified axis. - :ref:`View ` * - :meth:`~DataFrame.prod` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, min_count: typing.SupportsInt = 0, **kwargs)`` - Return the product of the values over the requested axis. - :ref:`View ` * - :meth:`~DataFrame.quantile` ``(q: typing.SupportsFloat = 0.5, axis: typing.SupportsInt = 0, numeric_only: bool = False, interpolation: str = 'linear', method: str = 'single')`` - Return values at the given quantile over requested axis. - :ref:`View ` * - :meth:`~DataFrame.sem` ``(axis: typing.SupportsInt = 0, skipna: bool = True, ddof: typing.SupportsInt = 1, numeric_only: bool = False, **kwargs)`` - Return unbiased standard error of the mean over requested axis. - :ref:`View ` * - :meth:`~DataFrame.skew` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return unbiased skew over requested axis. - :ref:`View ` * - :meth:`~DataFrame.std` ``(axis: typing.SupportsInt = 0, skipna: bool = True, ddof: typing.SupportsInt = 1, numeric_only: bool = False, **kwargs)`` - Return sample standard deviation over requested axis. - :ref:`View ` * - :meth:`~DataFrame.sum` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, min_count: typing.SupportsInt = 0, **kwargs)`` - Return the sum of the values over the requested axis. - :ref:`View ` * - :meth:`~DataFrame.value_counts` ``(subset: object = None, normalize: bool = False, sort: bool = True, ascending: bool = False, dropna: bool = True)`` - Return a Series containing counts of unique rows in the DataFrame. - :ref:`View ` * - :meth:`~DataFrame.var` ``(axis: typing.SupportsInt = 0, skipna: bool = True, ddof: typing.SupportsInt = 1, numeric_only: bool = False, **kwargs)`` - Return unbiased variance over requested axis. - :ref:`View ` Aggregation ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.agg` ``(func: object = None, axis: typing.SupportsInt = 0, *args, **kwargs)`` - Aggregate using one or more operations over the specified axis. - :ref:`View ` * - :meth:`~DataFrame.aggregate` ``(func: object = None, axis: typing.SupportsInt = 0, *args, **kwargs)`` - Alias for agg() - :ref:`View ` * - :meth:`~DataFrame.apply` ``(func: object, axis: typing.SupportsInt = 0, raw: bool = False, result_type: object = None, args: tuple = (), by_row: str = 'compat', engine: str = 'python', engine_kwargs: object = None, **kwargs)`` - Apply a function along an axis of the DataFrame. - :ref:`View ` * - :meth:`~DataFrame.applymap` ``(func: object, na_action: object = None, **kwargs)`` - Apply a function to each element of the DataFrame. - * - :meth:`~DataFrame.ewm` ``(com: object = None, span: object = None, halflife: object = None, alpha: object = None, min_periods: object = 0, adjust: bool = True, ignore_na: bool = False, axis: object = None, times: object = None, method: str = 'single')`` - Provide exponentially weighted (EW) calculations. - :ref:`View ` * - :meth:`~DataFrame.expanding` ``(min_periods: typing.SupportsInt = 1, axis: object = None, method: str = 'single')`` - Provide expanding transformations. - :ref:`View ` * - :meth:`~DataFrame.groupby` ``(by: object = None, axis: object = None, level: object = None, as_index: bool = True, sort: bool = True, group_keys: bool = True, observed: object = None, dropna: bool = True)`` - Group DataFrame using a mapper or by a Series of columns. - :ref:`View ` * - :meth:`~DataFrame.map` ``(func: object, na_action: object = None, **kwargs)`` - Apply a function to each element of the DataFrame. - * - :meth:`~DataFrame.pipe` ``(func: object, *args, **kwargs)`` - Apply chainable functions that expect DataFrames. - :ref:`View ` * - :meth:`~DataFrame.resample` ``(rule: str, axis: object = None, closed: object = None, label: object = None, convention: object = None, kind: object = None, on: object = None, level: object = None, origin: str = 'start_day', offset: object = None, group_keys: bool = False)`` - Resample time-series data. - :ref:`View ` * - :meth:`~DataFrame.rolling` ``(window: object, min_periods: object = None, center: bool = False, win_type: object = None, on: object = None, axis: object = None, closed: object = None, step: object = None, method: str = 'single')`` - Provide rolling window calculations. - :ref:`View ` * - :meth:`~DataFrame.transform` ``(func: object, axis: typing.SupportsInt = 0)`` - Call func on self producing a DataFrame with transformed values. - :ref:`View ` Arithmetic ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.add` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Addition of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.div` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Floating division of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.dot` ``(other: pandasCore.DataFrame)`` - Compute the matrix multiplication between the DataFrame and other. - * - :meth:`~DataFrame.floordiv` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Integer division of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.mod` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Modulo of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.mul` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Multiplication of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.pow` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Exponential power of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.radd` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Addition of dataframe and other, element-wise (binary operator ... - :ref:`View ` * - :meth:`~DataFrame.rdiv` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Floating division of dataframe and other, element-wise (binary ... - :ref:`View ` * - :meth:`~DataFrame.rfloordiv` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Integer division of dataframe and other, element-wise (binary o... - :ref:`View ` * - :meth:`~DataFrame.rmod` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Modulo of dataframe and other, element-wise (binary operator rm... - * - :meth:`~DataFrame.rmul` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Multiplication of dataframe and other, element-wise (binary ope... - :ref:`View ` * - :meth:`~DataFrame.rpow` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Exponential power of dataframe and other, element-wise (binary ... - :ref:`View ` * - :meth:`~DataFrame.rsub` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Subtraction of dataframe and other, element-wise (binary operat... - :ref:`View ` * - :meth:`~DataFrame.rtruediv` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Floating division of dataframe and other, element-wise (binary ... - * - :meth:`~DataFrame.sub` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Subtraction of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.truediv` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Get Floating division of dataframe and other, element-wise. - :ref:`View ` Comparison ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.__eq__` ``(arg0: object)`` - - * - :meth:`~DataFrame.__ge__` ``(arg0: object)`` - - * - :meth:`~DataFrame.__gt__` ``(arg0: object)`` - - * - :meth:`~DataFrame.__le__` ``(arg0: object)`` - - * - :meth:`~DataFrame.__lt__` ``(arg0: object)`` - - * - :meth:`~DataFrame.__ne__` ``(arg0: object)`` - - * - :meth:`~DataFrame.compare` ``(other: pandasCore.DataFrame, align_axis: object = 1, keep_shape: bool = False, keep_equal: bool = False, result_names: object = ('self', 'other'))`` - Compare to another DataFrame and show the differences. - * - :meth:`~DataFrame.eq` ``(other: object, axis: object = 'columns', level: object = None)`` - Get Equal to of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.equals` ``(other: pandasCore.DataFrame)`` - Test whether two objects contain the same elements. - * - :meth:`~DataFrame.ge` ``(other: object, axis: object = 'columns', level: object = None)`` - Get Greater than or equal to of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.gt` ``(other: object, axis: object = 'columns', level: object = None)`` - Get Greater than of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.le` ``(other: object, axis: object = 'columns', level: object = None)`` - Get Less than or equal to of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.lt` ``(other: object, axis: object = 'columns', level: object = None)`` - Get Less than of dataframe and other, element-wise. - :ref:`View ` * - :meth:`~DataFrame.ne` ``(other: object, axis: object = 'columns', level: object = None)`` - Get Not equal to of dataframe and other, element-wise. - :ref:`View ` Sorting ------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.rank` ``(axis: typing.SupportsInt = 0, method: str = 'average', numeric_only: bool = False, na_option: str = 'keep', ascending: bool = True, pct: bool = False)`` - Compute numerical data ranks (1 through n) along axis. - :ref:`View ` * - :meth:`~DataFrame.sort_index` ``(*, axis: typing.SupportsInt = 0, level: object = None, ascending: object = True, inplace: bool = False, kind: str = 'quicksort', na_position: str = 'last', sort_remaining: bool = True, ignore_index: bool = False, key: object = None)`` - Sort object by labels (along an axis). - :ref:`View ` * - :meth:`~DataFrame.sort_values` ``(by: object, *, axis: typing.SupportsInt = 0, ascending: object = True, inplace: bool = False, kind: str = 'quicksort', na_position: str = 'last', ignore_index: bool = False, key: object = None)`` - Sort by the values along either axis. - :ref:`View ` Reshaping --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.explode` ``(column: str, ignore_index: bool = False)`` - Transform each element of a list-like to a row. - :ref:`View ` * - :meth:`~DataFrame.melt` ``(id_vars: object = None, value_vars: object = None, var_name: object = None, value_name: str = 'value', col_level: object = None, ignore_index: bool = True)`` - Unpivot a DataFrame from wide to long format. - :ref:`View ` * - :meth:`~DataFrame.pivot` ``(*, columns: object, index: object = None, values: object = None)`` - Return reshaped DataFrame organized by given index / column values. - :ref:`View ` * - :meth:`~DataFrame.pivot_table` ``(values: object = None, index: object = None, columns: object = None, aggfunc: str = 'mean', fill_value: object = None, margins: bool = False, dropna: bool = True, margins_name: str = 'All', observed: object = None, sort: bool = True)`` - Create a spreadsheet-style pivot table as a DataFrame. - :ref:`View ` * - :meth:`~DataFrame.squeeze` ``(axis: object = None)`` - Squeeze 1 dimensional axis objects into scalars. - :ref:`View ` * - :meth:`~DataFrame.stack` ``(level: object = -1, dropna: object = None, sort: object = None, future_stack: bool = False)`` - Stack the prescribed level(s) from columns to index. - :ref:`View ` * - :meth:`~DataFrame.swapaxes` ``(axis1: typing.SupportsInt, axis2: typing.SupportsInt, copy: object = None)`` - Interchange axes and swap values axes appropriately. - :ref:`View ` * - :meth:`~DataFrame.transpose` ``(*args, copy: bool = False)`` - Transpose index and columns. - :ref:`View ` * - :meth:`~DataFrame.unstack` ``(level: object = -1, fill_value: object = None, sort: bool = True)`` - Pivot a level of the index labels to columns. - :ref:`View ` Combining --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.align` ``(other: pandasCore.DataFrame, join: str = 'outer', axis: object = None, level: object = None, copy: object = None, fill_value: object = None, method: object = None, limit: object = None, fill_axis: object = None, broadcast_axis: object = None)`` - Align two DataFrames on their axes. - :ref:`View ` * - :meth:`~DataFrame.combine` ``(other: pandasCore.DataFrame, func: object, fill_value: object = None, overwrite: bool = True)`` - Perform column-wise combine with another DataFrame. - * - :meth:`~DataFrame.combine_first` ``(other: pandasCore.DataFrame)`` - Update null elements with value in the same location in other. - * - :meth:`~DataFrame.join` ``(other: pandasCore.DataFrame, on: object = None, how: str = 'left', lsuffix: str = '', rsuffix: str = '', sort: bool = False, validate: object = None)`` - Join columns of another DataFrame. - * - :meth:`~DataFrame.merge` ``(right: pandasCore.DataFrame, how: str = 'inner', on: object = None, left_on: object = None, right_on: object = None, left_index: bool = False, right_index: bool = False, sort: bool = False, suffixes: tuple = ('_x', '_y'), copy: object = None, indicator: object = False, validate: object = None)`` - Merge DataFrame objects with a database-style join. - Time Series ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.asfreq` ``(freq: str, method: object = None, how: object = None, normalize: bool = False, fill_value: object = None)`` - Convert time series to specified frequency. - :ref:`View ` * - :meth:`~DataFrame.asof` ``(where: object, subset: object = None)`` - Return the last row(s) without any NaNs before where. - * - :meth:`~DataFrame.at_time` ``(time: str, asof: bool = False, axis: object = None)`` - Select values at particular time of day. - :ref:`View ` * - :meth:`~DataFrame.between_time` ``(start_time: str, end_time: str, inclusive: str = 'both', axis: object = None)`` - Select values between particular times of day. - :ref:`View ` * - :meth:`~DataFrame.diff` ``(periods: typing.SupportsInt = 1, axis: typing.SupportsInt = 0)`` - First discrete difference of element. - :ref:`View ` * - :meth:`~DataFrame.first_valid_index` ``()`` - Return index for first non-NA value or None, if no non-NA value is ... - :ref:`View ` * - :meth:`~DataFrame.last_valid_index` ``()`` - Return index for last non-NA value or None, if no non-NA value is f... - :ref:`View ` * - :meth:`~DataFrame.pct_change` ``(periods: typing.SupportsInt = 1, fill_method: object = None, limit: object = None, freq: object = None, **kwargs)`` - Percentage change between the current and a prior element. - :ref:`View ` * - :meth:`~DataFrame.shift` ``(periods: object = 1, freq: object = None, axis: typing.SupportsInt = 0, fill_value: object = None, suffix: object = None)`` - Shift index by desired number of periods. - :ref:`View ` * - :meth:`~DataFrame.to_period` ``(freq: object = None, axis: typing.SupportsInt = 0, copy: object = None)`` - Convert DataFrame from DatetimeIndex to PeriodIndex. - :ref:`View ` * - :meth:`~DataFrame.to_timestamp` ``(freq: object = None, how: str = 'start', axis: typing.SupportsInt = 0, copy: object = None)`` - Convert DataFrame from PeriodIndex to DatetimeIndex. - :ref:`View ` * - :meth:`~DataFrame.tz_convert` ``(tz: str, axis: typing.SupportsInt = 0, level: object = None, copy: object = None)`` - Convert tz-aware axis to target time zone. - :ref:`View ` * - :meth:`~DataFrame.tz_localize` ``(tz: object, axis: typing.SupportsInt = 0, level: object = None, copy: object = None, ambiguous: str = 'raise', nonexistent: str = 'raise')`` - Localize tz-naive index of a DataFrame to target time zone. - :ref:`View ` I/O --- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.to_clipboard` ``(excel: bool = True, sep: str = '\t')`` - Copy object to the system clipboard. - * - :meth:`~DataFrame.to_csv` ``(path_or_buf: object = None, *, sep: str = ',', na_rep: str = '', float_format: object = None, columns: object = None, header: bool = True, index: bool = True, index_label: object = None, mode: str = 'w', encoding: object = None, compression: object = 'infer', quoting: object = None, quotechar: str = '"', lineterminator: object = None, chunksize: object = None, date_format: object = None, doublequote: bool = True, escapechar: object = None, decimal: str = '.', errors: str = 'strict', storage_options: object = None)`` - Write object to a comma-separated values (csv) file. - :ref:`View ` * - :meth:`~DataFrame.to_dict` ``(orient: str = 'dict', *, into: object = None, index: bool = True)`` - Convert the DataFrame to a dictionary. - :ref:`View ` * - :meth:`~DataFrame.to_excel` ``(excel_writer: object, *, sheet_name: str = 'Sheet1', na_rep: str = '', float_format: object = None, columns: object = None, header: bool = True, index: bool = True, index_label: object = None, startrow: typing.SupportsInt = 0, startcol: typing.SupportsInt = 0, engine: object = None, merge_cells: bool = True, inf_rep: str = 'inf', freeze_panes: object = None, storage_options: object = None, engine_kwargs: object = None)`` - Write object to an Excel sheet. - :ref:`View ` * - :meth:`~DataFrame.to_feather` ``(path: object, **kwargs)`` - Write a DataFrame to the binary Feather format. Not implemented. - * - :meth:`~DataFrame.to_gbq` ``(destination_table: str, *, project_id: object = None, chunksize: object = None, reauth: bool = False, if_exists: str = 'fail', auth_local_webserver: bool = True, table_schema: object = None, location: object = None, progress_bar: bool = True, credentials: object = None)`` - Write a DataFrame to a Google BigQuery table. Not implemented. - * - :meth:`~DataFrame.to_hdf` ``(path_or_buf: str, *, key: str, mode: str = 'a', complevel: object = None, complib: object = None, append: bool = False, format: object = None, index: bool = True, min_itemsize: object = None, nan_rep: object = None, dropna: object = None, data_columns: object = None, errors: str = 'strict', encoding: str = 'UTF-8')`` - Write the contained data to an HDF5 file using HDFStore. - :ref:`View ` * - :meth:`~DataFrame.to_html` ``(buf: object = None, *, columns: object = None, col_space: object = None, header: bool = True, index: bool = True, na_rep: str = 'NaN', formatters: object = None, float_format: object = None, sparsify: object = None, index_names: bool = True, justify: object = None, max_rows: object = None, max_cols: object = None, show_dimensions: bool = False, decimal: str = '.', bold_rows: bool = True, classes: object = None, escape: bool = True, notebook: bool = False, border: object = None, table_id: object = None, render_links: bool = False, encoding: object = None)`` - Render a DataFrame as an HTML table. - :ref:`View ` * - :meth:`~DataFrame.to_json` ``(path_or_buf: object = None, *, orient: object = None, date_format: object = None, double_precision: typing.SupportsInt = 10, force_ascii: bool = True, date_unit: str = 'ms', default_handler: object = None, lines: bool = False, compression: object = 'infer', index: object = None, indent: object = None, storage_options: object = None, mode: str = 'w')`` - Convert the object to a JSON string. - :ref:`View ` * - :meth:`~DataFrame.to_latex` ``(buf: object = None, *, columns: object = None, header: bool = True, index: bool = True, na_rep: str = 'NaN', formatters: object = None, float_format: object = None, sparsify: object = None, index_names: bool = True, bold_rows: bool = False, column_format: object = None, longtable: object = None, escape: object = None, encoding: object = None, decimal: str = '.', multicolumn: object = None, multicolumn_format: object = None, multirow: object = None, caption: object = None, label: object = None, position: object = None)`` - Render object to a LaTeX tabular environment. - :ref:`View ` * - :meth:`~DataFrame.to_markdown` ``(buf: object = None, *, mode: str = 'wt', index: bool = True, storage_options: object = None)`` - Print DataFrame in Markdown-friendly format. - :ref:`View ` * - :meth:`~DataFrame.to_numpy` ``(dtype: object = None, copy: bool = False, na_value: object = None)`` - Convert the DataFrame to a NumPy array. - :ref:`View ` * - :meth:`~DataFrame.to_orc` ``(path: object = None, *, engine: str = 'pyarrow', index: object = None, engine_kwargs: object = None)`` - Write a DataFrame to the ORC format. Not implemented. - * - :meth:`~DataFrame.to_parquet` ``(path: object = None, *, engine: str = 'auto', compression: object = 'snappy', index: object = None, partition_cols: object = None, storage_options: object = None)`` - Write a DataFrame to the binary parquet format. Not implemented. - * - :meth:`~DataFrame.to_pickle` ``(path: str, *, compression: object = 'infer', protocol: object = 5, storage_options: object = None)`` - Pickle (serialize) object to file. Not implemented. - * - :meth:`~DataFrame.to_records` ``(index: bool = True, column_dtypes: object = None, index_dtypes: object = None)`` - Convert DataFrame to a list of tuples (records). - :ref:`View ` * - :meth:`~DataFrame.to_sql` ``(name: str, con: object, *, schema: object = None, if_exists: str = 'fail', index: bool = True, index_label: object = None, chunksize: object = None, dtype: object = None, method: object = None)`` - Write records stored in a DataFrame to a SQL database. Not implemen... - * - :meth:`~DataFrame.to_stata` ``(path: str, *, convert_dates: object = None, write_index: bool = True, byteorder: object = None, time_stamp: object = None, data_label: object = None, variable_labels: object = None, version: typing.SupportsInt = 114, convert_strl: object = None, compression: object = 'infer', storage_options: object = None, value_labels: object = None)`` - Export DataFrame object to Stata dta format. Not implemented. - * - :meth:`~DataFrame.to_string` ``(buf: object = None, *, columns: object = None, col_space: object = None, header: bool = True, index: bool = True, na_rep: str = 'NaN', formatters: object = None, float_format: object = None, sparsify: object = None, index_names: bool = True, justify: object = None, max_rows: object = None, max_cols: object = None, show_dimensions: bool = False, decimal: str = '.', line_width: object = None, min_rows: object = None, max_colwidth: object = None, encoding: object = None)`` - Render a DataFrame to a console-friendly tabular output. - :ref:`View ` * - :meth:`~DataFrame.to_xarray` ``()`` - Return an xarray object from the pandas object. Not implemented. - * - :meth:`~DataFrame.to_xml` ``(path_or_buffer: object = None, *, index: bool = True, root_name: str = 'data', row_name: str = 'row', na_rep: object = None, attr_cols: object = None, elem_cols: object = None, namespaces: object = None, prefix: object = None, encoding: str = 'utf-8', xml_declaration: bool = True, pretty_print: bool = True, parser: str = 'lxml', stylesheet: object = None, compression: object = 'infer', storage_options: object = None)`` - Render a DataFrame to an XML document. - :ref:`View ` Conversion ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.astype` ``(dtype: object, copy: object = None, errors: str = 'raise')`` - Cast a pandas object to a specified dtype. - :ref:`View ` * - :meth:`~DataFrame.bool` ``()`` - Return the bool of a single element DataFrame. - :ref:`View ` * - :meth:`~DataFrame.convert_dtypes` ``(infer_objects: bool = True, convert_string: bool = True, convert_integer: bool = True, convert_boolean: bool = True, convert_floating: bool = True, dtype_backend: str = 'numpy_nullable')`` - Convert columns to the best possible dtypes using dtypes supporting... - :ref:`View ` * - :meth:`~DataFrame.copy` ``(deep: bool = True)`` - Make a copy of this object's indices and data. - :ref:`View ` * - :meth:`~DataFrame.infer_objects` ``(copy: object = None)`` - Attempt to infer better dtypes for object columns. - :ref:`View ` Iteration --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.__contains__` ``(key: str)`` - Check if key is contained in DataFrame columns. - * - :meth:`~DataFrame.__iter__` ``()`` - Iterate over column names - * - :meth:`~DataFrame.__len__` ``()`` - Return the number of rows - * - :meth:`~DataFrame.items` ``()`` - Iterate over (column name, Series) pairs - :ref:`View ` * - :meth:`~DataFrame.iterrows` ``()`` - Iterate over DataFrame rows as (index, dict) pairs - :ref:`View ` * - :meth:`~DataFrame.itertuples` ``(index: bool = True, name: str = 'Pandas')`` - Iterate over DataFrame rows as namedtuples - :ref:`View ` * - :meth:`~DataFrame.keys` ``()`` - Return the column labels (alias for columns property) - :ref:`View ` Set Operations -------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.drop_duplicates` ``(subset: object = None, *, keep: str = 'first', inplace: bool = False, ignore_index: bool = False)`` - Return DataFrame with duplicate rows removed. - :ref:`View ` * - :meth:`~DataFrame.duplicated` ``(subset: object = None, keep: str = 'first')`` - Return boolean Series denoting duplicate rows. - :ref:`View ` * - :meth:`~DataFrame.isin` ``(values: collections.abc.Sequence[typing.SupportsFloat])`` - Whether each element in the DataFrame is contained in values. - :ref:`View ` Datetime Methods ---------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.round` ``(decimals: typing.SupportsInt = 0, *args, **kwargs)`` - Round a DataFrame to a variable number of decimal places. - :ref:`View ` Other Methods ------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~DataFrame.__hash__` - - * - :meth:`~DataFrame.__repr__` ``()`` - - * - :meth:`~DataFrame.__str__` ``()`` - - * - :meth:`~DataFrame.abs` ``()`` - Return a DataFrame with absolute numeric value of each element. - :ref:`View ` * - :meth:`~DataFrame.add_prefix` ``(prefix: str, axis: object = None)`` - Prefix labels with string prefix. - :ref:`View ` * - :meth:`~DataFrame.add_suffix` ``(suffix: str, axis: object = None)`` - Suffix labels with string suffix. - :ref:`View ` * - :meth:`~DataFrame.all` ``(axis: typing.SupportsInt = 0, bool_only: bool = False, skipna: bool = True, **kwargs)`` - Return whether all elements are True, potentially over an axis. - :ref:`View ` * - :meth:`~DataFrame.any` ``(*, axis: typing.SupportsInt = 0, bool_only: bool = False, skipna: bool = True, **kwargs)`` - Return whether any element is True, potentially over an axis. - :ref:`View ` * - :meth:`~DataFrame.boxplot` ``(column: object = None, by: object = None, ax: object = None, fontsize: object = None, rot: typing.SupportsInt = 0, grid: bool = True, figsize: object = None, layout: object = None, return_type: object = None, backend: object = None)`` - Make a box plot from DataFrame columns. Not implemented. - :ref:`View ` * - :meth:`~DataFrame.clip` ``(lower: object = None, upper: object = None, *, axis: object = None, inplace: bool = False, **kwargs)`` - Trim values at input threshold(s). - :ref:`View ` * - :meth:`~DataFrame.corr` ``(method: str = 'pearson', min_periods: typing.SupportsInt = 1, numeric_only: bool = False)`` - Compute pairwise correlation of columns. - :ref:`View ` * - :meth:`~DataFrame.corrwith` ``(other: pandasCore.DataFrame, axis: typing.SupportsInt = 0, drop: bool = False, method: str = 'pearson', numeric_only: bool = False)`` - Compute pairwise correlation. - * - :meth:`~DataFrame.cov` ``(min_periods: object = None, ddof: object = 1, numeric_only: bool = False)`` - Compute pairwise covariance of columns. - :ref:`View ` * - :meth:`~DataFrame.divide` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Alias for div() - :ref:`View ` * - :meth:`~DataFrame.eval` ``(expr: str, *, inplace: bool = False, **kwargs)`` - Evaluate a string describing operations on DataFrame columns. - :ref:`View ` * - :meth:`~DataFrame.filter` ``(items: object = None, like: object = None, regex: object = None, axis: object = None)`` - Subset the DataFrame rows or columns according to the specified ind... - :ref:`View ` * - :meth:`~DataFrame.hist` ``(data: pandasCore.DataFrame, column: object = None, by: object = None, grid: bool = True, xlabelsize: object = None, xrot: object = None, ylabelsize: object = None, yrot: object = None, ax: object = None, sharex: bool = False, sharey: bool = False, figsize: object = None, layout: object = None, bins: typing.SupportsInt = 10, backend: object = None, legend: bool = False, **kwargs)`` - Make a histogram of the DataFrame's columns. Not implemented. - :ref:`View ` * - :meth:`~DataFrame.info` ``(verbose: object = None, buf: object = None, max_cols: object = None, memory_usage: object = None, show_counts: object = None)`` - Print a concise summary of a DataFrame - :ref:`View ` * - :meth:`~DataFrame.isetitem` ``(loc: typing.SupportsInt, value: object)`` - Set item by position. - * - :meth:`~DataFrame.memory_usage` ``(index: bool = True, deep: bool = False)`` - Return the memory usage of each column in bytes. - :ref:`View ` * - :meth:`~DataFrame.multiply` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Alias for mul() - :ref:`View ` * - :meth:`~DataFrame.product` ``(axis: typing.SupportsInt = 0, skipna: bool = True, numeric_only: bool = False, min_count: typing.SupportsInt = 0, **kwargs)`` - Alias for prod() - :ref:`View ` * - :meth:`~DataFrame.reindex_like` ``(other: pandasCore.DataFrame, method: object = None, copy: object = None, limit: object = None, tolerance: object = None)`` - Return an object with matching indices as other object. - * - :meth:`~DataFrame.select_dtypes` ``(include: object = None, exclude: object = None)`` - Return a subset of the DataFrame's columns based on the column dtypes. - :ref:`View ` * - :meth:`~DataFrame.set_flags` ``(*, copy: bool = False, allows_duplicate_labels: object = None)`` - Return a new object with updated flags. - :ref:`View ` * - :meth:`~DataFrame.subtract` ``(other: object, axis: object = 'columns', level: object = None, fill_value: object = None)`` - Alias for sub() - :ref:`View ` * - :meth:`~DataFrame.truncate` ``(before: object = None, after: object = None, axis: object = None, copy: object = None)`` - Truncate a Series or DataFrame before and after some index value. - :ref:`View ` Code Examples ------------- The following examples are extracted from the test suite. .. _example-dataframe-t-0: .. dropdown:: T (test_df_sorting_reshaping.py:157) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 147 :emphasize-lines: 11 f_print_header("Test: transpose / T") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Test transpose method t1 = df.transpose() f_print_info(f"transpose shape: {t1.shape}") # Test T property t2 = df.T f_print_info(f"T property shape: {t2.shape}") # Shapes should match if t1.shape == t2.shape: f_print_success("transpose/T: passed") return True else: f_print_error("transpose/T: shapes don't match") return False .. _example-dataframe-columns-1: .. dropdown:: columns (test_dataframe.py:43) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 33 :emphasize-lines: 11 f_print_header("Test: DataFrame __init__ from dict") try: # Create DataFrame from dict df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Check shape ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)") # Check columns cols = list(df.columns) ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B") # Check nrows/ncols ctx.assert_equal(3, df.nrows, "nrows is 3") ctx.assert_equal(2, df.ncols, "ncols is 2") # Check len ctx.assert_equal(3, len(df), "len(df) is 3") # Check __getitem__ .. _example-dataframe-empty-2: .. dropdown:: empty (test_example.py:65) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 55 :emphasize-lines: 11 # Check shape shape = df.shape if shape == (0, 0): f_print_success(f"Shape is correct: {shape}") else: f_print_error(f"Shape is wrong: {shape}, expected (0, 0)") return False # Check empty property if df.empty: f_print_success("empty property is True") else: f_print_error("empty property should be True") return False # Check len if len(df) == 0: f_print_success("len(df) is 0") else: f_print_error(f"len(df) is {len(df)}, expected 0") .. _example-dataframe-ncols-3: .. dropdown:: ncols (test_dataframe.py:48) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 38 :emphasize-lines: 11 # Check shape ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)") # Check columns cols = list(df.columns) ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B") # Check nrows/ncols ctx.assert_equal(3, df.nrows, "nrows is 3") ctx.assert_equal(2, df.ncols, "ncols is 2") # Check len ctx.assert_equal(3, len(df), "len(df) is 3") # Check __getitem__ col_a = df['A'] ctx.assert_equal(3, len(col_a), "Column A has 3 elements") f_print_success("DataFrame __init__ from dict: All checks passed") return True .. _example-dataframe-nrows-4: .. dropdown:: nrows (test_dataframe.py:47) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 37 :emphasize-lines: 11 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Check shape ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)") # Check columns cols = list(df.columns) ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B") # Check nrows/ncols ctx.assert_equal(3, df.nrows, "nrows is 3") ctx.assert_equal(2, df.ncols, "ncols is 2") # Check len ctx.assert_equal(3, len(df), "len(df) is 3") # Check __getitem__ col_a = df['A'] ctx.assert_equal(3, len(col_a), "Column A has 3 elements") f_print_success("DataFrame __init__ from dict: All checks passed") .. _example-dataframe-shape-5: .. dropdown:: shape (test_dataframe.py:40) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 30 :emphasize-lines: 11 def test_dataframe_init_from_dict(): """Test DataFrame construction from dictionary""" f_print_header("Test: DataFrame __init__ from dict") try: # Create DataFrame from dict df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Check shape ctx.assert_equal((3, 2), df.shape, "Shape is (3, 2)") # Check columns cols = list(df.columns) ctx.assert_true('A' in cols and 'B' in cols, "Columns contain A and B") # Check nrows/ncols ctx.assert_equal(3, df.nrows, "nrows is 3") ctx.assert_equal(2, df.ncols, "ncols is 2") # Check len .. _example-dataframe-sparse-6: .. dropdown:: sparse (test_sparse_accessor.py:80) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 70 :emphasize-lines: 11 assert coo_obj.nnz == 2, f"Expected 2 non-zero elements" def test_dataframe_sparse_density(): """Test DataFrame.sparse.density""" global tests_run tests_run += 1 df = pandasCore.DataFrame({ "A": [0.0, 1.0, 0.0], "B": [0.0, 0.0, 2.0] }) density = df.sparse.density # 2 non-zero out of 6 = 0.333... assert abs(density - 0.333) < 0.01, f"Expected ~0.333, got {density}" def test_dataframe_sparse_to_dense(): """Test DataFrame.sparse.to_dense()""" global tests_run tests_run += 1 df = pandasCore.DataFrame({ "A": [0.0, 1.0, 0.0], "B": [0.0, 0.0, 2.0] .. _example-dataframe-dunder-initdunder--7: .. dropdown:: __init__ (test_concat_comp.py:43) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 33 :emphasize-lines: 11 # ==================== concat axis=0 column union/intersection Tests ==================== def test_concat_axis0_outer_union(): """Test concat axis=0 with join='outer' - columns from all DFs""" f_print_header("concat axis=0 outer union") pd_df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) pd_df2 = pd.DataFrame({'B': [5, 6], 'C': [7, 8]}) pd_result = pd.concat([pd_df1, pd_df2], axis=0, join='outer') pc_df1 = pandasCore.DataFrame({'A': [1, 2], 'B': [3, 4]}) pc_df2 = pandasCore.DataFrame({'B': [5, 6], 'C': [7, 8]}) pc_result = pandasCore.concat([pc_df1, pc_df2], axis=0, join='outer') ctx.assert_equal(len(pd_result), len(pc_result), "outer union row count") ctx.assert_equal(len(pd_result.columns), len(pc_result.columns), "outer union col count") # Check NaN fill for missing columns ctx.assert_true(pd.isna(pd_result['A'].iloc[2]), "pandas A[2] is NaN") def test_concat_axis0_inner(): .. _example-dataframe-first-8: .. dropdown:: first (test_df_sorting_reshaping.py:523) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 513 :emphasize-lines: 11 def test_first_last(): """Test first and last methods""" f_print_header("Test: first / last") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # These methods are for time series with DatetimeIndex try: first_df = df.first('3D') f_print_info(f"first('3D') shape: {first_df.shape}") except Exception as e: f_print_info(f"first (expected - needs DatetimeIndex): {e}") try: last_df = df.last('3D') f_print_info(f"last('3D') shape: {last_df.shape}") except Exception as e: f_print_info(f"last (expected - needs DatetimeIndex): {e}") .. _example-dataframe-get-9: .. dropdown:: get (test_dataframe.py:251) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 241 :emphasize-lines: 11 def test_dataframe_get(): """Test get() method""" f_print_header("Test: DataFrame.get") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # Get existing column col_a = df.get('A') ctx.assert_true(col_a is not None, "get('A') returns value") ctx.assert_equal(2, len(col_a), "get('A') has 2 elements") # Get non-existing column with default result = df.get('Z', default='not_found') ctx.assert_equal('not_found', result, "get('Z') returns default") # Get non-existing column without default result_none = df.get('Z') ctx.assert_true(result_none is None, "get('Z') returns None") .. _example-dataframe-head-10: .. dropdown:: head (test_dataframe.py:114) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 104 :emphasize-lines: 11 def test_dataframe_head_tail(): """Test head() and tail() methods""" f_print_header("Test: DataFrame.head/tail") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Test head head_df = df.head(3) ctx.assert_equal(3, head_df.shape[0], "head(3) returns 3 rows") # Test tail tail_df = df.tail(2) ctx.assert_equal(2, tail_df.shape[0], "tail(2) returns 2 rows") # Test default head (5 rows) head_default = df.head() ctx.assert_equal(5, head_default.shape[0], "head() returns 5 rows") .. _example-dataframe-idxmax-11: .. dropdown:: idxmax (test_dataframe_phase3.py:294) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 284 :emphasize-lines: 11 # Index Operations Tests # ============================================================================= def test_idxmax_idxmin(): """Test idxmax() and idxmin() methods""" f_print_header("Test: DataFrame.idxmax/idxmin") try: df = pandasCore.DataFrame({'A': [1.0, 3.0, 2.0], 'B': [6.0, 4.0, 5.0]}) idxmax_result = df.idxmax() idxmin_result = df.idxmin() # Index of max in A is row 1, in B is row 0 ctx.assert_true('A' in idxmax_result, "idxmax returns column A") ctx.assert_true('A' in idxmin_result, "idxmin returns column A") f_print_success("DataFrame.idxmax/idxmin: All checks passed") return True except Exception as e: .. _example-dataframe-idxmin-12: .. dropdown:: idxmin (test_dataframe_phase3.py:295) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 285 :emphasize-lines: 11 # ============================================================================= def test_idxmax_idxmin(): """Test idxmax() and idxmin() methods""" f_print_header("Test: DataFrame.idxmax/idxmin") try: df = pandasCore.DataFrame({'A': [1.0, 3.0, 2.0], 'B': [6.0, 4.0, 5.0]}) idxmax_result = df.idxmax() idxmin_result = df.idxmin() # Index of max in A is row 1, in B is row 0 ctx.assert_true('A' in idxmax_result, "idxmax returns column A") ctx.assert_true('A' in idxmin_result, "idxmin returns column A") f_print_success("DataFrame.idxmax/idxmin: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-last-13: .. dropdown:: last (test_df_sorting_reshaping.py:529) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 519 :emphasize-lines: 11 df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # These methods are for time series with DatetimeIndex try: first_df = df.first('3D') f_print_info(f"first('3D') shape: {first_df.shape}") except Exception as e: f_print_info(f"first (expected - needs DatetimeIndex): {e}") try: last_df = df.last('3D') f_print_info(f"last('3D') shape: {last_df.shape}") except Exception as e: f_print_info(f"last (expected - needs DatetimeIndex): {e}") f_print_success("first/last: passed") return True except Exception as e: f_print_error(f"first/last failed: {e}") return False .. _example-dataframe-nlargest-14: .. dropdown:: nlargest (test_dataframe_phase3.py:505) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 495 :emphasize-lines: 11 return False def test_nlargest_nsmallest(): """Test nlargest() and nsmallest() methods""" f_print_header("Test: DataFrame.nlargest/nsmallest") try: df = pandasCore.DataFrame({'A': [1.0, 5.0, 3.0, 4.0, 2.0]}) largest = df.nlargest(2, 'A') smallest = df.nsmallest(2, 'A') ctx.assert_equal(2, largest.shape[0], "nlargest returns 2 rows") ctx.assert_equal(2, smallest.shape[0], "nsmallest returns 2 rows") f_print_success("DataFrame.nlargest/nsmallest: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-nsmallest-15: .. dropdown:: nsmallest (test_dataframe_phase3.py:506) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 496 :emphasize-lines: 11 def test_nlargest_nsmallest(): """Test nlargest() and nsmallest() methods""" f_print_header("Test: DataFrame.nlargest/nsmallest") try: df = pandasCore.DataFrame({'A': [1.0, 5.0, 3.0, 4.0, 2.0]}) largest = df.nlargest(2, 'A') smallest = df.nsmallest(2, 'A') ctx.assert_equal(2, largest.shape[0], "nlargest returns 2 rows") ctx.assert_equal(2, smallest.shape[0], "nsmallest returns 2 rows") f_print_success("DataFrame.nlargest/nsmallest: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-query-16: .. dropdown:: query (test_dataframe_phase2.py:329) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 319 :emphasize-lines: 11 return False def test_query(): """Test query method""" f_print_header("Test: query") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0], 'B': [5.0, 4.0, 3.0, 2.0, 1.0]}) result = df.query("A > 2") ctx.assert_true(result.shape[0] < df.shape[0], "Query filters rows") ctx.assert_true(result.shape[0] == 3, "Query returns 3 rows (A=3,4,5)") f_print_success("query: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-sample-17: .. dropdown:: sample (test_dataframe.py:340) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 330 :emphasize-lines: 11 def test_dataframe_sample(): """Test sample() method""" f_print_header("Test: DataFrame.sample") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]}) # Sample by n sampled = df.sample(n=3, random_state=42) ctx.assert_equal(3, sampled.shape[0], "sample(n=3) returns 3 rows") # Sample by frac sampled_frac = df.sample(frac=0.5, random_state=42) ctx.assert_equal(5, sampled_frac.shape[0], "sample(frac=0.5) returns 5 rows") f_print_success("DataFrame.sample: All checks passed") return True except Exception as e: .. _example-dataframe-tail-18: .. dropdown:: tail (test_dataframe.py:118) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 108 :emphasize-lines: 11 f_print_header("Test: DataFrame.head/tail") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Test head head_df = df.head(3) ctx.assert_equal(3, head_df.shape[0], "head(3) returns 3 rows") # Test tail tail_df = df.tail(2) ctx.assert_equal(2, tail_df.shape[0], "tail(2) returns 2 rows") # Test default head (5 rows) head_default = df.head() ctx.assert_equal(5, head_default.shape[0], "head() returns 5 rows") f_print_success("DataFrame.head/tail: All checks passed") return True except Exception as e: .. _example-dataframe-take-19: .. dropdown:: take (test_dataframe.py:321) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 311 :emphasize-lines: 11 def test_dataframe_take(): """Test take() method""" f_print_header("Test: DataFrame.take") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Take specific indices taken = df.take([0, 2, 4]) ctx.assert_equal(3, taken.shape[0], "take([0,2,4]) returns 3 rows") f_print_success("DataFrame.take: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-where-20: .. dropdown:: where (test_signature_phase13.py:302) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 292 :emphasize-lines: 11 df2 = pandasCore.DataFrame({'A': [5.0, 6.0], 'B': [7.0, 8.0]}) df.update(df2, join='left', overwrite=True, filter_func=None, errors='ignore') def test_where_signature(): """Test DataFrame.where has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) cond = pandasCore.DataFrame({'A': [True, False], 'B': [False, True]}) result = df.where(cond, other=float('nan'), inplace=False, axis=None, level=None) assert isinstance(result, pandasCore.DataFrame) def test_xs_signature(): """Test DataFrame.xs has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) try: result = df.xs('0', axis=0, level=None, drop_level=True) .. _example-dataframe-xs-21: .. dropdown:: xs (test_signature_phase13.py:312) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 302 :emphasize-lines: 11 result = df.where(cond, other=float('nan'), inplace=False, axis=None, level=None) assert isinstance(result, pandasCore.DataFrame) def test_xs_signature(): """Test DataFrame.xs has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) try: result = df.xs('0', axis=0, level=None, drop_level=True) except (RuntimeError, KeyError) as e: print(f" Note: xs error (expected with non-existing key): {e}") def f_main(): """Main test function.""" global tests_run, tests_passed, tests_failed f_print_header("Phase 13: DataFrame Missing Parameters Signature Tests") .. _example-dataframe-assign-22: .. dropdown:: assign (test_dataframe_phase2.py:370) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 360 :emphasize-lines: 11 return False def test_assign(): """Test assign method""" f_print_header("Test: assign") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.assign(B=[4.0, 5.0, 6.0], C=[7.0, 8.0, 9.0]) cols = list(result.columns) ctx.assert_true('A' in cols, "Original column A exists") ctx.assert_true('B' in cols, "New column B exists") ctx.assert_true('C' in cols, "New column C exists") ctx.assert_equal(3, len(cols), "Three columns after assign") f_print_success("assign: All checks passed") return True except Exception as e: .. _example-dataframe-drop-23: .. dropdown:: drop (test_dataframe_phase2.py:103) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 93 :emphasize-lines: 11 def test_drop(): """Test drop method""" f_print_header("Test: drop") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0], 'C': [7.0, 8.0, 9.0]}) # Drop columns result = df.drop(columns=['B']) cols = list(result.columns) ctx.assert_equal(2, len(cols), "Two columns after drop") ctx.assert_true('B' not in cols, "Column 'B' removed") f_print_success("drop: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-droplevel-24: .. dropdown:: droplevel (test_df_sorting_reshaping.py:108) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 98 :emphasize-lines: 11 def test_droplevel(): """Test droplevel method""" f_print_header("Test: droplevel") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # droplevel with int (may fail if no MultiIndex) try: result = df.droplevel(0, axis=0) f_print_info(f"droplevel result shape: {result.shape}") except Exception as e: f_print_info(f"droplevel (no MultiIndex): {e}") f_print_success("droplevel: passed") return True except Exception as e: f_print_error(f"droplevel failed: {e}") return False .. _example-dataframe-insert-25: .. dropdown:: insert (test_dataframe_phase2.py:392) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 382 :emphasize-lines: 11 return False def test_insert(): """Test insert method""" f_print_header("Test: insert") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) df.insert(1, 'X', [10.0, 20.0]) cols = list(df.columns) ctx.assert_equal(3, len(cols), "Three columns after insert") ctx.assert_true('X' in cols, "Column X inserted") f_print_success("insert: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-pop-26: .. dropdown:: pop (test_dataframe_phase2.py:411) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 401 :emphasize-lines: 11 return False def test_pop(): """Test pop method""" f_print_header("Test: pop") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0], 'C': [5.0, 6.0]}) popped = df.pop('B') cols = list(df.columns) ctx.assert_equal(2, len(popped), "Popped column has 2 values") ctx.assert_true('B' not in cols, "Column B removed from DataFrame") ctx.assert_equal(2, len(cols), "Two columns remain") f_print_success("pop: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-reindex-27: .. dropdown:: reindex (test_dataframe_phase2.py:487) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 477 :emphasize-lines: 11 def test_reindex(): """Test reindex method""" f_print_header("Test: reindex") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Reindex columns result = df.reindex(['A'], axis=1) ctx.assert_true(result.ncols == 1, "One column after reindex") f_print_success("reindex: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False def f_main(): .. _example-dataframe-rename-28: .. dropdown:: rename (test_dataframe_phase2.py:81) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 71 :emphasize-lines: 11 f_print_error(f"Exception: {e}") return False def test_rename(): """Test rename method""" f_print_header("Test: rename") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) result = df.rename(columns={'A': 'X', 'B': 'Y'}) cols = list(result.columns) ctx.assert_true('X' in cols, "Column 'X' exists after rename") ctx.assert_true('Y' in cols, "Column 'Y' exists after rename") ctx.assert_true('A' not in cols, "Column 'A' no longer exists") f_print_success("rename: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-rename_axis-29: .. dropdown:: rename_axis (test_dataframe_phase2.py:469) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 459 :emphasize-lines: 11 return False def test_rename_axis(): """Test rename_axis method""" f_print_header("Test: rename_axis") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) result = df.rename_axis("my_axis", axis=0) ctx.assert_true(result.shape == df.shape, "Shape preserved after rename_axis") f_print_success("rename_axis: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False def test_reindex(): .. _example-dataframe-reorder_levels-30: .. dropdown:: reorder_levels (test_df_sorting_reshaping.py:457) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 447 :emphasize-lines: 11 def test_reorder_levels(): """Test reorder_levels method""" f_print_header("Test: reorder_levels") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # This may fail without a proper MultiIndex try: reordered = df.reorder_levels([0], axis=0) f_print_info(f"reorder_levels shape: {reordered.shape}") except Exception as e: f_print_info(f"reorder_levels (expected - no MultiIndex): {e}") f_print_success("reorder_levels: passed") return True except Exception as e: f_print_error(f"reorder_levels failed: {e}") return False .. _example-dataframe-replace-31: .. dropdown:: replace (test_dataframe_phase2.py:288) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 278 :emphasize-lines: 11 return False def test_replace(): """Test replace method""" f_print_header("Test: replace") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 2.0, 4.0]}) result = df.replace(2.0, 99.0) # Check that 2.0 was replaced with 99.0 col_a = result['A'] # Column A had one 2.0 at index 1, should now have 99.0 ctx.assert_equal(99.0, float(col_a[1]), "2.0 replaced with 99.0 in column A") f_print_success("replace: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-set_axis-32: .. dropdown:: set_axis (test_df_sorting_reshaping.py:84) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 74 :emphasize-lines: 11 def test_set_axis(): """Test set_axis method""" f_print_header("Test: set_axis") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Set row labels new_df = df.set_axis(['x', 'y', 'z'], axis=0) f_print_info(f"set_axis row shape: {new_df.shape}") # Set column labels new_df2 = df.set_axis(['X', 'Y'], axis=1) f_print_info(f"set_axis col shape: {new_df2.shape}") f_print_success("set_axis: passed") return True except Exception as e: .. _example-dataframe-set_index-33: .. dropdown:: set_index (test_df_phase6.py:255) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 245 :emphasize-lines: 11 return False def test_set_index(): """Test set_index method""" f_print_header("Test: set_index") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.set_index('A') f_print_info(f"set_index shape: {result.shape}") f_print_info(f"set_index columns: {list(result.columns)}") # After set_index, we should have one less column if result.shape[1] == 1: # B column only f_print_success("set_index: passed") else: f_print_error(f"set_index: expected 1 column, got {result.shape[1]}") return False .. _example-dataframe-swaplevel-34: .. dropdown:: swaplevel (test_df_sorting_reshaping.py:479) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 469 :emphasize-lines: 11 def test_swaplevel(): """Test swaplevel method""" f_print_header("Test: swaplevel") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # This may fail without a proper MultiIndex try: swapped = df.swaplevel(-2, -1, axis=0) f_print_info(f"swaplevel shape: {swapped.shape}") except Exception as e: f_print_info(f"swaplevel (expected - no MultiIndex): {e}") f_print_success("swaplevel: passed") return True except Exception as e: f_print_error(f"swaplevel failed: {e}") return False .. _example-dataframe-update-35: .. dropdown:: update (test_signature_phase13.py:293) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 283 :emphasize-lines: 11 coerce_float=False, nrows=None) assert isinstance(result, pandasCore.DataFrame) def test_update_signature(): """Test DataFrame.update has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) df2 = pandasCore.DataFrame({'A': [5.0, 6.0], 'B': [7.0, 8.0]}) df.update(df2, join='left', overwrite=True, filter_func=None, errors='ignore') def test_where_signature(): """Test DataFrame.where has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) cond = pandasCore.DataFrame({'A': [True, False], 'B': [False, True]}) result = df.where(cond, other=float('nan'), inplace=False, axis=None, level=None) assert isinstance(result, pandasCore.DataFrame) .. _example-dataframe-backfill-36: .. dropdown:: backfill (test_df_phase6.py:219) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 209 :emphasize-lines: 11 return False def test_backfill(): """Test backfill method""" f_print_header("Test: backfill") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.backfill() f_print_info(f"backfill shape: {result.shape}") f_print_success("backfill: passed") return True except Exception as e: f_print_error(f"backfill failed: {e}") return False .. _example-dataframe-bfill-37: .. dropdown:: bfill (test_dataframe_phase2.py:269) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 259 :emphasize-lines: 11 return False def test_bfill(): """Test bfill method""" f_print_header("Test: bfill") try: df = pandasCore.DataFrame({'A': [float('nan'), 2.0, 3.0]}) result = df.bfill() # After bfill, the NaN in position [0,0] should be filled with 2.0 isna_result = result.isna() ctx.assert_equal(False, isna_result['A'][0], "NaN filled by bfill") f_print_success("bfill: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-dropna-38: .. dropdown:: dropna (test_dataframe_phase2.py:185) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 175 :emphasize-lines: 11 return False def test_dropna(): """Test dropna method""" f_print_header("Test: dropna") try: df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.dropna() # Should have fewer rows ctx.assert_true(result.shape[0] < df.shape[0], "Fewer rows after dropna") f_print_success("dropna: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-ffill-39: .. dropdown:: ffill (test_dataframe_phase2.py:249) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 239 :emphasize-lines: 11 return False def test_ffill(): """Test ffill method""" f_print_header("Test: ffill") try: df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [float('nan'), 2.0, float('nan')]}) result = df.ffill() # After ffill, the NaN in position [1,0] should be filled with 1.0 isna_result = result.isna() # The first column should have no NaN after ffill (first value propagates forward) ctx.assert_equal(False, isna_result['A'][1], "NaN filled by ffill") f_print_success("ffill: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-fillna-40: .. dropdown:: fillna (test_dataframe_phase2.py:162) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 152 :emphasize-lines: 11 def test_fillna(): """Test fillna method""" f_print_header("Test: fillna") try: df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, float('nan')]}) # Fill with scalar result = df.fillna(value=0.0) # Check that NaN values are replaced - access by column name isna_result = result.isna() # isna returns DataFrame with 1.0 for True, 0.0 for False # Check that no column has any NaN (all values should be 0.0) has_na_a = any(v == 1.0 for v in isna_result['A']) has_na_b = any(v == 1.0 for v in isna_result['B']) ctx.assert_true(not has_na_a and not has_na_b, "No NaN values after fillna") f_print_success("fillna: All checks passed") return True .. _example-dataframe-interpolate-41: .. dropdown:: interpolate (test_dataframe_phase2.py:432) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 422 :emphasize-lines: 11 return False def test_interpolate(): """Test interpolate method""" f_print_header("Test: interpolate") try: df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0]}) result = df.interpolate() # After linear interpolation, the NaN should be filled with 2.0 isna_result = result.isna() ctx.assert_equal(False, isna_result['A'][1], "NaN filled by interpolate") f_print_success("interpolate: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-isna-42: .. dropdown:: isna (test_dataframe_phase2.py:204) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 194 :emphasize-lines: 11 def test_isna_notna(): """Test isna and notna methods""" f_print_header("Test: isna/notna") try: df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, float('nan')]}) # Test isna isna_result = df.isna() ctx.assert_equal(3, len(isna_result), "isna returns 3 rows") ctx.assert_equal(True, isna_result['A'][1], "NaN detected in row 1, col A") # Test notna notna_result = df.notna() ctx.assert_equal(True, notna_result['A'][0], "Non-NaN detected in row 0, col A") ctx.assert_equal(False, notna_result['A'][1], "NaN detected in row 1, col A (notna=False)") f_print_success("isna/notna: All checks passed") return True .. _example-dataframe-isnull-43: .. dropdown:: isnull (test_dataframe_phase2.py:228) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 218 :emphasize-lines: 11 def test_isnull_notnull(): """Test isnull and notnull methods (aliases)""" f_print_header("Test: isnull/notnull") try: df = pandasCore.DataFrame({'A': [1.0, float('nan')]}) # Test isnull (alias for isna) isnull_result = df.isnull() ctx.assert_equal(True, isnull_result['A'][1], "isnull detects NaN") # Test notnull (alias for notna) notnull_result = df.notnull() ctx.assert_equal(True, notnull_result['A'][0], "notnull detects non-NaN") f_print_success("isnull/notnull: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-notna-44: .. dropdown:: notna (test_dataframe_phase2.py:209) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 199 :emphasize-lines: 11 try: df = pandasCore.DataFrame({'A': [1.0, float('nan'), 3.0], 'B': [4.0, 5.0, float('nan')]}) # Test isna isna_result = df.isna() ctx.assert_equal(3, len(isna_result), "isna returns 3 rows") ctx.assert_equal(True, isna_result['A'][1], "NaN detected in row 1, col A") # Test notna notna_result = df.notna() ctx.assert_equal(True, notna_result['A'][0], "Non-NaN detected in row 0, col A") ctx.assert_equal(False, notna_result['A'][1], "NaN detected in row 1, col A (notna=False)") f_print_success("isna/notna: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-notnull-45: .. dropdown:: notnull (test_dataframe_phase2.py:232) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 222 :emphasize-lines: 11 f_print_header("Test: isnull/notnull") try: df = pandasCore.DataFrame({'A': [1.0, float('nan')]}) # Test isnull (alias for isna) isnull_result = df.isnull() ctx.assert_equal(True, isnull_result['A'][1], "isnull detects NaN") # Test notnull (alias for notna) notnull_result = df.notnull() ctx.assert_equal(True, notnull_result['A'][0], "notnull detects non-NaN") f_print_success("isnull/notnull: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False def test_ffill(): .. _example-dataframe-pad-46: .. dropdown:: pad (test_df_phase6.py:237) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 227 :emphasize-lines: 11 return False def test_pad(): """Test pad method""" f_print_header("Test: pad") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.pad() f_print_info(f"pad shape: {result.shape}") f_print_success("pad: passed") return True except Exception as e: f_print_error(f"pad failed: {e}") return False .. _example-dataframe-count-47: .. dropdown:: count (test_dataframe_phase3.py:252) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 242 :emphasize-lines: 11 # Count and Unique Tests # ============================================================================= def test_count(): """Test count() method""" f_print_header("Test: DataFrame.count") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.count() ctx.assert_equal(3, result['A'], "count A = 3") ctx.assert_equal(3, result['B'], "count B = 3") f_print_success("DataFrame.count: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-cummax-48: .. dropdown:: cummax (test_dataframe_phase3.py:359) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 349 :emphasize-lines: 11 def test_cummin_cummax(): """Test cummin() and cummax() methods""" f_print_header("Test: DataFrame.cummin/cummax") try: df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0]}) cummin_result = df.cummin() cummax_result = df.cummax() ctx.assert_equal((3, 1), cummin_result.shape, "cummin shape is (3, 1)") ctx.assert_equal((3, 1), cummax_result.shape, "cummax shape is (3, 1)") f_print_success("DataFrame.cummin/cummax: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-cummin-49: .. dropdown:: cummin (test_dataframe_phase3.py:358) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 348 :emphasize-lines: 11 return False def test_cummin_cummax(): """Test cummin() and cummax() methods""" f_print_header("Test: DataFrame.cummin/cummax") try: df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0]}) cummin_result = df.cummin() cummax_result = df.cummax() ctx.assert_equal((3, 1), cummin_result.shape, "cummin shape is (3, 1)") ctx.assert_equal((3, 1), cummax_result.shape, "cummax shape is (3, 1)") f_print_success("DataFrame.cummin/cummax: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-cumprod-50: .. dropdown:: cumprod (test_dataframe_phase3.py:339) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 329 :emphasize-lines: 11 return False def test_cumprod(): """Test cumprod() method""" f_print_header("Test: DataFrame.cumprod") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.cumprod() ctx.assert_equal((3, 1), result.shape, "cumprod shape is (3, 1)") # Values should be [1, 2, 6] f_print_success("DataFrame.cumprod: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-cumsum-51: .. dropdown:: cumsum (test_dataframe_phase3.py:320) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 310 :emphasize-lines: 11 # Cumulative Operations Tests # ============================================================================= def test_cumsum(): """Test cumsum() method""" f_print_header("Test: DataFrame.cumsum") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.cumsum() ctx.assert_equal((3, 1), result.shape, "cumsum shape is (3, 1)") # Values should be [1, 3, 6] f_print_success("DataFrame.cumsum: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-describe-52: .. dropdown:: describe (test_dataframe_phase3.py:653) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 643 :emphasize-lines: 11 # Describe and Mode Tests # ============================================================================= def test_describe(): """Test describe() method""" f_print_header("Test: DataFrame.describe") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) result = df.describe() ctx.assert_true(result.nrows > 0, "describe returns statistics") ctx.assert_true(result.ncols > 0, "describe has columns") f_print_success("DataFrame.describe: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-kurt-53: .. dropdown:: kurt (test_dataframe_phase3.py:203) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 193 :emphasize-lines: 11 return False def test_kurt(): """Test kurt() and kurtosis() methods""" f_print_header("Test: DataFrame.kurt/kurtosis") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) kurt_result = df.kurt() kurtosis_result = df.kurtosis() # Both should be the same (kurtosis is alias) ctx.assert_true('A' in kurt_result, "kurt returns column A") ctx.assert_true('A' in kurtosis_result, "kurtosis returns column A") f_print_success("DataFrame.kurt/kurtosis: All checks passed") return True except Exception as e: .. _example-dataframe-kurtosis-54: .. dropdown:: kurtosis (test_dataframe_phase3.py:204) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 194 :emphasize-lines: 11 def test_kurt(): """Test kurt() and kurtosis() methods""" f_print_header("Test: DataFrame.kurt/kurtosis") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) kurt_result = df.kurt() kurtosis_result = df.kurtosis() # Both should be the same (kurtosis is alias) ctx.assert_true('A' in kurt_result, "kurt returns column A") ctx.assert_true('A' in kurtosis_result, "kurtosis returns column A") f_print_success("DataFrame.kurt/kurtosis: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-max-55: .. dropdown:: max (test_dataframe_phase3.py:120) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 110 :emphasize-lines: 11 def test_min_max(): """Test min() and max() methods""" f_print_header("Test: DataFrame.min/max") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) min_result = df.min() max_result = df.max() ctx.assert_close(1.0, min_result['A'], "min A = 1.0") ctx.assert_close(4.0, min_result['B'], "min B = 4.0") ctx.assert_close(3.0, max_result['A'], "max A = 3.0") ctx.assert_close(6.0, max_result['B'], "max B = 6.0") f_print_success("DataFrame.min/max: All checks passed") return True except Exception as e: .. _example-dataframe-mean-56: .. dropdown:: mean (test_dataframe_phase3.py:81) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 71 :emphasize-lines: 11 return False def test_mean(): """Test mean() method""" f_print_header("Test: DataFrame.mean") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.mean() ctx.assert_close(2.0, result['A'], "mean A = 2.0") ctx.assert_close(5.0, result['B'], "mean B = 5.0") f_print_success("DataFrame.mean: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-median-57: .. dropdown:: median (test_dataframe_phase3.py:100) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 90 :emphasize-lines: 11 return False def test_median(): """Test median() method""" f_print_header("Test: DataFrame.median") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.median() ctx.assert_close(2.0, result['A'], "median A = 2.0") ctx.assert_close(5.0, result['B'], "median B = 5.0") f_print_success("DataFrame.median: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-min-58: .. dropdown:: min (test_dataframe_phase3.py:119) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 109 :emphasize-lines: 11 return False def test_min_max(): """Test min() and max() methods""" f_print_header("Test: DataFrame.min/max") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) min_result = df.min() max_result = df.max() ctx.assert_close(1.0, min_result['A'], "min A = 1.0") ctx.assert_close(4.0, min_result['B'], "min B = 4.0") ctx.assert_close(3.0, max_result['A'], "max A = 3.0") ctx.assert_close(6.0, max_result['B'], "max B = 6.0") f_print_success("DataFrame.min/max: All checks passed") return True .. _example-dataframe-mode-59: .. dropdown:: mode (test_dataframe_phase3.py:672) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 662 :emphasize-lines: 11 return False def test_mode(): """Test mode() method""" f_print_header("Test: DataFrame.mode") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 2.0, 3.0]}) result = df.mode() ctx.assert_true(result.ncols >= 1, "mode returns DataFrame") f_print_success("DataFrame.mode: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-nunique-60: .. dropdown:: nunique (test_dataframe_phase3.py:271) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 261 :emphasize-lines: 11 return False def test_nunique(): """Test nunique() method""" f_print_header("Test: DataFrame.nunique") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 2.0, 3.0], 'B': [1.0, 1.0, 1.0, 2.0]}) result = df.nunique() ctx.assert_equal(3, result['A'], "nunique A = 3") ctx.assert_equal(2, result['B'], "nunique B = 2") f_print_success("DataFrame.nunique: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-prod-61: .. dropdown:: prod (test_dataframe_phase3.py:62) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 52 :emphasize-lines: 11 return False def test_prod(): """Test prod() method""" f_print_header("Test: DataFrame.prod") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 3.0, 4.0]}) result = df.prod() ctx.assert_close(6.0, result['A'], "prod A = 6.0") ctx.assert_close(24.0, result['B'], "prod B = 24.0") f_print_success("DataFrame.prod: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-quantile-62: .. dropdown:: quantile (test_dataframe_phase3.py:226) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 216 :emphasize-lines: 11 def test_quantile(): """Test quantile() method""" f_print_header("Test: DataFrame.quantile") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Median (q=0.5) result = df.quantile(0.5) ctx.assert_close(3.0, result['A'], "quantile 0.5 = 3.0") # Q1 (q=0.25) result_q1 = df.quantile(0.25) ctx.assert_true('A' in result_q1, "quantile 0.25 returns column A") f_print_success("DataFrame.quantile: All checks passed") return True except Exception as e: .. _example-dataframe-sem-63: .. dropdown:: sem (test_dataframe_phase3.py:164) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 154 :emphasize-lines: 11 return False def test_sem(): """Test sem() method - standard error of mean""" f_print_header("Test: DataFrame.sem") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.sem() # sem = std / sqrt(n) = 1.0 / sqrt(3) ≈ 0.577 expected = 1.0 / math.sqrt(3) ctx.assert_close(expected, result['A'], "sem A correct", tol=0.01) f_print_success("DataFrame.sem: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-skew-64: .. dropdown:: skew (test_dataframe_phase3.py:184) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 174 :emphasize-lines: 11 return False def test_skew(): """Test skew() method""" f_print_header("Test: DataFrame.skew") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) result = df.skew() # Symmetric distribution should have skew near 0 ctx.assert_close(0.0, result['A'], "skew A = 0.0", tol=0.1) f_print_success("DataFrame.skew: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-std-65: .. dropdown:: std (test_dataframe_phase3.py:142) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 132 :emphasize-lines: 11 return False def test_std_var(): """Test std() and var() methods""" f_print_header("Test: DataFrame.std/var") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) std_result = df.std() var_result = df.var() # std of [1,2,3] with ddof=1 is 1.0 ctx.assert_close(1.0, std_result['A'], "std A = 1.0") ctx.assert_close(1.0, var_result['A'], "var A = 1.0") f_print_success("DataFrame.std/var: All checks passed") return True except Exception as e: .. _example-dataframe-sum-66: .. dropdown:: sum (test_dataframe_phase3.py:43) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 33 :emphasize-lines: 11 # Basic Statistics Tests # ============================================================================= def test_sum(): """Test sum() method""" f_print_header("Test: DataFrame.sum") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.sum() ctx.assert_close(6.0, result['A'], "sum A = 6.0") ctx.assert_close(15.0, result['B'], "sum B = 15.0") f_print_success("DataFrame.sum: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-value_counts-67: .. dropdown:: value_counts (test_dataframe_phase3.py:690) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 680 :emphasize-lines: 11 return False def test_value_counts(): """Test value_counts() method""" f_print_header("Test: DataFrame.value_counts") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 2.0, 3.0]}) result = df.value_counts() ctx.assert_true(isinstance(result, dict), "value_counts returns dict") f_print_success("DataFrame.value_counts: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-var-68: .. dropdown:: var (test_dataframe_phase3.py:143) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 133 :emphasize-lines: 11 def test_std_var(): """Test std() and var() methods""" f_print_header("Test: DataFrame.std/var") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) std_result = df.std() var_result = df.var() # std of [1,2,3] with ddof=1 is 1.0 ctx.assert_close(1.0, std_result['A'], "std A = 1.0") ctx.assert_close(1.0, var_result['A'], "var A = 1.0") f_print_success("DataFrame.std/var: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-agg-69: .. dropdown:: agg (test_dataframe_phase3.py:531) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 521 :emphasize-lines: 11 # ============================================================================= def test_agg(): """Test agg() method""" f_print_header("Test: DataFrame.agg") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Single function result = df.agg('sum') ctx.assert_equal(1, result.shape[0], "agg('sum') returns 1 row") # Multiple functions result_multi = df.agg(['sum', 'mean']) ctx.assert_equal(2, result_multi.shape[0], "agg(['sum', 'mean']) returns 2 rows") f_print_success("DataFrame.agg: All checks passed") return True except Exception as e: .. _example-dataframe-aggregate-70: .. dropdown:: aggregate (test_dataframe_phase3.py:553) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 543 :emphasize-lines: 11 return False def test_aggregate(): """Test aggregate() method (alias for agg)""" f_print_header("Test: DataFrame.aggregate") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.aggregate('mean') ctx.assert_equal(1, result.shape[0], "aggregate returns 1 row") f_print_success("DataFrame.aggregate: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-apply-71: .. dropdown:: apply (test_dataframe_phase3.py:571) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 561 :emphasize-lines: 11 return False def test_apply(): """Test apply() method""" f_print_header("Test: DataFrame.apply") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.apply('sum') ctx.assert_equal(1, result.shape[0], "apply('sum') returns 1 row") f_print_success("DataFrame.apply: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-ewm-72: .. dropdown:: ewm (test_df_phase6.py:177) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 167 :emphasize-lines: 11 def test_ewm(): """Test ewm method""" f_print_header("Test: ewm") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # EWM mean ewm = df.ewm(span=2) result = ewm.mean() f_print_info(f"EWM mean shape: {result.shape}") f_print_success("ewm: mean passed") # EWM with com parameter ewm_com = df.ewm(com=0.5) result_com = ewm_com.mean() f_print_success("ewm: com parameter passed") return True .. _example-dataframe-expanding-73: .. dropdown:: expanding (test_df_phase6.py:153) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 143 :emphasize-lines: 11 def test_expanding(): """Test expanding method""" f_print_header("Test: expanding") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Expanding sum expanding = df.expanding() result = expanding.sum() f_print_info(f"Expanding sum shape: {result.shape}") f_print_success("expanding: sum passed") # Expanding mean result_mean = expanding.mean() f_print_success("expanding: mean passed") return True .. _example-dataframe-groupby-74: .. dropdown:: groupby (test_df_phase6.py:93) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 83 :emphasize-lines: 11 """Test groupby method""" f_print_header("Test: groupby") try: df = pandasCore.DataFrame({ 'category': [1.0, 1.0, 2.0, 2.0, 3.0], 'value': [10.0, 20.0, 30.0, 40.0, 50.0] }) # Groupby and sum grouped = df.groupby('category') result = grouped.sum() f_print_info(f"Grouped sum shape: {result.shape}") f_print_success("groupby: sum passed") # Groupby and mean result_mean = grouped.mean() f_print_info(f"Grouped mean shape: {result_mean.shape}") f_print_success("groupby: mean passed") # Test other aggregations .. _example-dataframe-pipe-75: .. dropdown:: pipe (test_dataframe_phase3.py:708) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 698 :emphasize-lines: 11 return False def test_pipe(): """Test pipe() method""" f_print_header("Test: DataFrame.pipe") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.pipe('sum') ctx.assert_true(result.shape[0] == 1, "pipe('sum') returns aggregation") f_print_success("DataFrame.pipe: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-resample-76: .. dropdown:: resample (test_df_phase6.py:436) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 426 :emphasize-lines: 11 def test_resample(): """Test resample method""" f_print_header("Test: resample") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: resample requires DatetimeIndex try: resampled = df.resample('D') f_print_info("resample object created") f_print_success("resample: passed") except Exception: f_print_info("resample: skipped (requires DatetimeIndex)") return True except Exception as e: f_print_error(f"resample failed: {e}") return False .. _example-dataframe-rolling-77: .. dropdown:: rolling (test_df_phase6.py:124) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 114 :emphasize-lines: 11 def test_rolling(): """Test rolling method""" f_print_header("Test: rolling") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Rolling sum rolling = df.rolling(window=2) result = rolling.sum() f_print_info(f"Rolling sum shape: {result.shape}") f_print_success("rolling: sum passed") # Rolling mean result_mean = rolling.mean() f_print_success("rolling: mean passed") # Rolling min/max result_min = rolling.min() .. _example-dataframe-transform-78: .. dropdown:: transform (test_dataframe_phase3.py:589) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 579 :emphasize-lines: 11 return False def test_transform(): """Test transform() method""" f_print_header("Test: DataFrame.transform") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.transform('cumsum') ctx.assert_equal(df.shape, result.shape, "transform preserves shape") f_print_success("DataFrame.transform: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-add-79: .. dropdown:: add (test_dataframe_phase4.py:43) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 33 :emphasize-lines: 11 # ============================================================================= def test_add(): """Test add operation""" f_print_header("Test: add") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Scalar add result = df.add(10.0) col_a = result['A'] ctx.assert_close(11.0, col_a[0], "add scalar: A[0] = 11.0") ctx.assert_close(12.0, col_a[1], "add scalar: A[1] = 12.0") ctx.assert_close(13.0, col_a[2], "add scalar: A[2] = 13.0") f_print_success("add: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-div-80: .. dropdown:: div (test_dataframe_phase4.py:109) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 99 :emphasize-lines: 11 def test_div(): """Test div operation""" f_print_header("Test: div") try: df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0], 'B': [40.0, 50.0, 60.0]}) # Scalar div result = df.div(10.0) col_a = result['A'] ctx.assert_close(1.0, col_a[0], "div scalar: A[0] = 1.0") ctx.assert_close(2.0, col_a[1], "div scalar: A[1] = 2.0") ctx.assert_close(3.0, col_a[2], "div scalar: A[2] = 3.0") f_print_success("div: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-floordiv-81: .. dropdown:: floordiv (test_dataframe_phase4.py:151) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 141 :emphasize-lines: 11 def test_floordiv(): """Test floordiv operation""" f_print_header("Test: floordiv") try: df = pandasCore.DataFrame({'A': [7.0, 17.0, 27.0], 'B': [45.0, 55.0, 65.0]}) # Scalar floordiv result = df.floordiv(10.0) col_a = result['A'] ctx.assert_close(0.0, col_a[0], "floordiv scalar: A[0] = 0.0") ctx.assert_close(1.0, col_a[1], "floordiv scalar: A[1] = 1.0") ctx.assert_close(2.0, col_a[2], "floordiv scalar: A[2] = 2.0") f_print_success("floordiv: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-mod-82: .. dropdown:: mod (test_dataframe_phase4.py:173) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 163 :emphasize-lines: 11 def test_mod(): """Test mod operation""" f_print_header("Test: mod") try: df = pandasCore.DataFrame({'A': [7.0, 17.0, 27.0], 'B': [45.0, 55.0, 65.0]}) # Scalar mod result = df.mod(10.0) col_a = result['A'] ctx.assert_close(7.0, col_a[0], "mod scalar: A[0] = 7.0") ctx.assert_close(7.0, col_a[1], "mod scalar: A[1] = 7.0") ctx.assert_close(7.0, col_a[2], "mod scalar: A[2] = 7.0") f_print_success("mod: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-mul-83: .. dropdown:: mul (test_dataframe_phase4.py:87) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 77 :emphasize-lines: 11 def test_mul(): """Test mul operation""" f_print_header("Test: mul") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Scalar mul result = df.mul(2.0) col_a = result['A'] ctx.assert_close(2.0, col_a[0], "mul scalar: A[0] = 2.0") ctx.assert_close(4.0, col_a[1], "mul scalar: A[1] = 4.0") ctx.assert_close(6.0, col_a[2], "mul scalar: A[2] = 6.0") f_print_success("mul: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-pow-84: .. dropdown:: pow (test_dataframe_phase4.py:195) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 185 :emphasize-lines: 11 def test_pow(): """Test pow operation""" f_print_header("Test: pow") try: df = pandasCore.DataFrame({'A': [2.0, 3.0, 4.0], 'B': [1.0, 2.0, 3.0]}) # Scalar pow result = df.pow(2.0) col_a = result['A'] ctx.assert_close(4.0, col_a[0], "pow scalar: A[0] = 4.0") ctx.assert_close(9.0, col_a[1], "pow scalar: A[1] = 9.0") ctx.assert_close(16.0, col_a[2], "pow scalar: A[2] = 16.0") f_print_success("pow: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-radd-85: .. dropdown:: radd (test_dataframe_phase4.py:221) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 211 :emphasize-lines: 11 # ============================================================================= def test_radd(): """Test radd operation""" f_print_header("Test: radd") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Scalar radd (scalar + df) result = df.radd(10.0) col_a = result['A'] ctx.assert_close(11.0, col_a[0], "radd scalar: A[0] = 11.0") f_print_success("radd: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-rdiv-86: .. dropdown:: rdiv (test_dataframe_phase4.py:284) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 274 :emphasize-lines: 11 def test_rdiv(): """Test rdiv operation""" f_print_header("Test: rdiv") try: df = pandasCore.DataFrame({'A': [2.0, 4.0, 5.0], 'B': [1.0, 2.0, 10.0]}) # Scalar rdiv (scalar / df) result = df.rdiv(10.0) col_a = result['A'] ctx.assert_close(5.0, col_a[0], "rdiv scalar: A[0] = 5.0") # 10 / 2 ctx.assert_close(2.5, col_a[1], "rdiv scalar: A[1] = 2.5") # 10 / 4 ctx.assert_close(2.0, col_a[2], "rdiv scalar: A[2] = 2.0") # 10 / 5 f_print_success("rdiv: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-rfloordiv-87: .. dropdown:: rfloordiv (test_dataframe_phase4.py:306) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 296 :emphasize-lines: 11 def test_rfloordiv(): """Test rfloordiv operation""" f_print_header("Test: rfloordiv") try: df = pandasCore.DataFrame({'A': [3.0, 4.0, 5.0]}) # Scalar rfloordiv (scalar // df) result = df.rfloordiv(10.0) col_a = result['A'] ctx.assert_close(3.0, col_a[0], "rfloordiv scalar: A[0] = 3.0") # floor(10 / 3) ctx.assert_close(2.0, col_a[1], "rfloordiv scalar: A[1] = 2.0") # floor(10 / 4) ctx.assert_close(2.0, col_a[2], "rfloordiv scalar: A[2] = 2.0") # floor(10 / 5) f_print_success("rfloordiv: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-rmul-88: .. dropdown:: rmul (test_dataframe_phase4.py:263) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 253 :emphasize-lines: 11 def test_rmul(): """Test rmul operation""" f_print_header("Test: rmul") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Scalar rmul (scalar * df) result = df.rmul(3.0) col_a = result['A'] ctx.assert_close(3.0, col_a[0], "rmul scalar: A[0] = 3.0") ctx.assert_close(6.0, col_a[1], "rmul scalar: A[1] = 6.0") f_print_success("rmul: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-rpow-89: .. dropdown:: rpow (test_dataframe_phase4.py:328) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 318 :emphasize-lines: 11 def test_rpow(): """Test rpow operation""" f_print_header("Test: rpow") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Scalar rpow (scalar ** df) result = df.rpow(2.0) col_a = result['A'] ctx.assert_close(2.0, col_a[0], "rpow scalar: A[0] = 2.0") # 2**1 ctx.assert_close(4.0, col_a[1], "rpow scalar: A[1] = 4.0") # 2**2 ctx.assert_close(8.0, col_a[2], "rpow scalar: A[2] = 8.0") # 2**3 f_print_success("rpow: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-rsub-90: .. dropdown:: rsub (test_dataframe_phase4.py:241) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 231 :emphasize-lines: 11 def test_rsub(): """Test rsub operation""" f_print_header("Test: rsub") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Scalar rsub (scalar - df) result = df.rsub(10.0) col_a = result['A'] ctx.assert_close(9.0, col_a[0], "rsub scalar: A[0] = 9.0") # 10 - 1 ctx.assert_close(8.0, col_a[1], "rsub scalar: A[1] = 8.0") # 10 - 2 ctx.assert_close(7.0, col_a[2], "rsub scalar: A[2] = 7.0") # 10 - 3 f_print_success("rsub: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-sub-91: .. dropdown:: sub (test_dataframe_phase4.py:65) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 55 :emphasize-lines: 11 def test_sub(): """Test sub operation""" f_print_header("Test: sub") try: df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0], 'B': [40.0, 50.0, 60.0]}) # Scalar sub result = df.sub(5.0) col_a = result['A'] ctx.assert_close(5.0, col_a[0], "sub scalar: A[0] = 5.0") ctx.assert_close(15.0, col_a[1], "sub scalar: A[1] = 15.0") ctx.assert_close(25.0, col_a[2], "sub scalar: A[2] = 25.0") f_print_success("sub: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-truediv-92: .. dropdown:: truediv (test_dataframe_phase4.py:131) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 121 :emphasize-lines: 11 def test_truediv(): """Test truediv operation""" f_print_header("Test: truediv") try: df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0], 'B': [40.0, 50.0, 60.0]}) # Scalar truediv result = df.truediv(10.0) col_a = result['A'] ctx.assert_close(1.0, col_a[0], "truediv scalar: A[0] = 1.0") f_print_success("truediv: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-eq-93: .. dropdown:: eq (test_dataframe_phase4.py:531) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 521 :emphasize-lines: 11 # ============================================================================= def test_eq(): """Test eq (equal) comparison""" f_print_header("Test: eq") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 2.0, 2.0]}) # Scalar comparison result = df.eq(2.0) col_a = result['A'] ctx.assert_close(0.0, col_a[0], "eq: A[0] != 2, result = 0") ctx.assert_close(1.0, col_a[1], "eq: A[1] == 2, result = 1") ctx.assert_close(0.0, col_a[2], "eq: A[2] != 2, result = 0") f_print_success("eq: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-ge-94: .. dropdown:: ge (test_dataframe_phase4.py:641) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 631 :emphasize-lines: 11 def test_ge(): """Test ge (greater than or equal) comparison""" f_print_header("Test: ge") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Scalar comparison result = df.ge(2.0) col_a = result['A'] ctx.assert_close(0.0, col_a[0], "ge: A[0] < 2, result = 0") ctx.assert_close(1.0, col_a[1], "ge: A[1] >= 2, result = 1") ctx.assert_close(1.0, col_a[2], "ge: A[2] >= 2, result = 1") f_print_success("ge: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-gt-95: .. dropdown:: gt (test_dataframe_phase4.py:619) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 609 :emphasize-lines: 11 def test_gt(): """Test gt (greater than) comparison""" f_print_header("Test: gt") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Scalar comparison result = df.gt(2.0) col_a = result['A'] ctx.assert_close(0.0, col_a[0], "gt: A[0] < 2, result = 0") ctx.assert_close(0.0, col_a[1], "gt: A[1] == 2, result = 0") ctx.assert_close(1.0, col_a[2], "gt: A[2] > 2, result = 1") f_print_success("gt: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-le-96: .. dropdown:: le (test_dataframe_phase4.py:597) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 587 :emphasize-lines: 11 def test_le(): """Test le (less than or equal) comparison""" f_print_header("Test: le") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Scalar comparison result = df.le(2.0) col_a = result['A'] ctx.assert_close(1.0, col_a[0], "le: A[0] <= 2, result = 1") ctx.assert_close(1.0, col_a[1], "le: A[1] <= 2, result = 1") ctx.assert_close(0.0, col_a[2], "le: A[2] > 2, result = 0") f_print_success("le: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-lt-97: .. dropdown:: lt (test_dataframe_phase4.py:575) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 565 :emphasize-lines: 11 def test_lt(): """Test lt (less than) comparison""" f_print_header("Test: lt") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Scalar comparison result = df.lt(2.0) col_a = result['A'] ctx.assert_close(1.0, col_a[0], "lt: A[0] < 2, result = 1") ctx.assert_close(0.0, col_a[1], "lt: A[1] == 2, result = 0") ctx.assert_close(0.0, col_a[2], "lt: A[2] > 2, result = 0") f_print_success("lt: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-ne-98: .. dropdown:: ne (test_dataframe_phase4.py:553) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 543 :emphasize-lines: 11 def test_ne(): """Test ne (not equal) comparison""" f_print_header("Test: ne") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 2.0, 2.0]}) # Scalar comparison result = df.ne(2.0) col_a = result['A'] ctx.assert_close(1.0, col_a[0], "ne: A[0] != 2, result = 1") ctx.assert_close(0.0, col_a[1], "ne: A[1] == 2, result = 0") ctx.assert_close(1.0, col_a[2], "ne: A[2] != 2, result = 1") f_print_success("ne: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-rank-99: .. dropdown:: rank (test_dataframe_phase3.py:486) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 476 :emphasize-lines: 11 # Ranking and Selection Tests # ============================================================================= def test_rank(): """Test rank() method""" f_print_header("Test: DataFrame.rank") try: df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0]}) result = df.rank() ctx.assert_equal((3, 1), result.shape, "rank shape is (3, 1)") # Ranks should be [3, 1, 2] f_print_success("DataFrame.rank: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-sort_index-100: .. dropdown:: sort_index (test_df_sorting_reshaping.py:62) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 52 :emphasize-lines: 11 def test_sort_index(): """Test sort_index method""" f_print_header("Test: sort_index") try: df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0], 'B': [6.0, 4.0, 5.0]}) # Sort by index ascending sorted_df = df.sort_index() f_print_info(f"Sorted shape: {sorted_df.shape}") # Sort by index descending sorted_desc = df.sort_index(ascending=False) f_print_success("sort_index: passed") return True except Exception as e: f_print_error(f"sort_index failed: {e}") .. _example-dataframe-sort_values-101: .. dropdown:: sort_values (test_df_sorting_reshaping.py:35) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 25 :emphasize-lines: 11 def test_sort_values(): """Test sort_values method""" f_print_header("Test: sort_values") try: df = pandasCore.DataFrame({'A': [3.0, 1.0, 2.0], 'B': [6.0, 4.0, 5.0]}) # Sort by single column ascending sorted_df = df.sort_values('A') f_print_info(f"Original shape: {df.shape}") f_print_info(f"Sorted shape: {sorted_df.shape}") # Sort by single column descending sorted_desc = df.sort_values('A', ascending=False) f_print_success("sort_values: single column ascending/descending passed") # Sort by list of columns sorted_multi = df.sort_values(['A', 'B']) f_print_success("sort_values: multiple columns passed") .. _example-dataframe-explode-102: .. dropdown:: explode (test_df_sorting_reshaping.py:298) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 288 :emphasize-lines: 11 f_print_header("Test: explode") try: # Note: our implementation works with comma-separated strings df = pandasCore.DataFrame({ 'id': [1.0, 2.0], 'tags': [1.0, 2.0] # Simple values (no list support in this binding) }) # This may not expand if values aren't comma-separated strings exploded = df.explode('tags') f_print_info(f"Exploded shape: {exploded.shape}") f_print_success("explode: passed") return True except Exception as e: f_print_error(f"explode failed: {e}") return False .. _example-dataframe-melt-103: .. dropdown:: melt (test_df_sorting_reshaping.py:185) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 175 :emphasize-lines: 11 f_print_header("Test: melt") try: df = pandasCore.DataFrame({ 'id': [1.0, 2.0], 'A': [10.0, 20.0], 'B': [30.0, 40.0] }) # Melt with id_vars melted = df.melt(id_vars=['id'], value_vars=['A', 'B']) f_print_info(f"Melted shape: {melted.shape}") # Melt without id_vars melted2 = df.melt() f_print_info(f"Melted (no id) shape: {melted2.shape}") f_print_success("melt: passed") return True except Exception as e: .. _example-dataframe-pivot-104: .. dropdown:: pivot (test_df_sorting_reshaping.py:212) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 202 :emphasize-lines: 11 f_print_header("Test: pivot") try: df = pandasCore.DataFrame({ 'idx': [1.0, 1.0, 2.0, 2.0], 'col': [1.0, 2.0, 1.0, 2.0], 'val': [10.0, 20.0, 30.0, 40.0] }) # Basic pivot pivoted = df.pivot(index='idx', columns='col', values='val') f_print_info(f"Pivoted shape: {pivoted.shape}") f_print_success("pivot: passed") return True except Exception as e: f_print_error(f"pivot failed: {e}") return False .. _example-dataframe-pivot_table-105: .. dropdown:: pivot_table (test_df_sorting_reshaping.py:235) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 225 :emphasize-lines: 11 f_print_header("Test: pivot_table") try: df = pandasCore.DataFrame({ 'region': [1.0, 1.0, 2.0, 2.0], 'product': [1.0, 2.0, 1.0, 2.0], 'sales': [100.0, 200.0, 150.0, 250.0] }) # Basic pivot_table with mean aggregation pt = df.pivot_table(values='sales', index='region', columns='product', aggfunc='mean') f_print_info(f"Pivot table shape: {pt.shape}") # Pivot table with sum pt_sum = df.pivot_table(values='sales', index='region', columns='product', aggfunc='sum') f_print_info(f"Pivot table (sum) shape: {pt_sum.shape}") f_print_success("pivot_table: passed") return True except Exception as e: .. _example-dataframe-squeeze-106: .. dropdown:: squeeze (test_df_sorting_reshaping.py:316) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 306 :emphasize-lines: 11 return False def test_squeeze(): """Test squeeze method""" f_print_header("Test: squeeze") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) squeezed = df.squeeze() f_print_info(f"Squeezed shape: {squeezed.shape}") f_print_success("squeeze: passed") return True except Exception as e: f_print_error(f"squeeze failed: {e}") return False .. _example-dataframe-stack-107: .. dropdown:: stack (test_df_sorting_reshaping.py:257) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 247 :emphasize-lines: 11 return False def test_stack(): """Test stack method""" f_print_header("Test: stack") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) stacked = df.stack() f_print_info(f"Stacked shape: {stacked.shape}") f_print_success("stack: passed") return True except Exception as e: f_print_error(f"stack failed: {e}") return False .. _example-dataframe-swapaxes-108: .. dropdown:: swapaxes (test_df_sorting_reshaping.py:129) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 119 :emphasize-lines: 11 def test_swapaxes(): """Test swapaxes method""" f_print_header("Test: swapaxes") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Swap axes (equivalent to transpose) swapped = df.swapaxes(0, 1) f_print_info(f"Original shape: {df.shape}, Swapped shape: {swapped.shape}") # Shape should be transposed if df.shape[0] == swapped.shape[1] and df.shape[1] == swapped.shape[0]: f_print_success("swapaxes: passed") return True else: f_print_error("swapaxes: shape mismatch") return False .. _example-dataframe-transpose-109: .. dropdown:: transpose (test_df_sorting_reshaping.py:153) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 143 :emphasize-lines: 11 def test_transpose(): """Test transpose and T property""" f_print_header("Test: transpose / T") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Test transpose method t1 = df.transpose() f_print_info(f"transpose shape: {t1.shape}") # Test T property t2 = df.T f_print_info(f"T property shape: {t2.shape}") # Shapes should match if t1.shape == t2.shape: f_print_success("transpose/T: passed") return True .. _example-dataframe-unstack-110: .. dropdown:: unstack (test_df_sorting_reshaping.py:275) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 265 :emphasize-lines: 11 return False def test_unstack(): """Test unstack method""" f_print_header("Test: unstack") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) unstacked = df.unstack() f_print_info(f"Unstacked shape: {unstacked.shape}") f_print_success("unstack: passed") return True except Exception as e: f_print_error(f"unstack failed: {e}") return False .. _example-dataframe-align-111: .. dropdown:: align (test_signature_phase13.py:53) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 43 :emphasize-lines: 11 return False def test_align_signature(): """Test DataFrame.align has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) df2 = pandasCore.DataFrame({'A': [5.0, 6.0], 'B': [7.0, 8.0]}) result = df.align(df2, join='outer', axis=None, level=None, copy=None, fill_value=None, method=None, limit=None, fill_axis=None, broadcast_axis=None) assert isinstance(result, tuple), "align should return tuple" def test_set_axis_signature(): """Test DataFrame.set_axis has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) .. _example-dataframe-asfreq-112: .. dropdown:: asfreq (test_df_phase6.py:282) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 272 :emphasize-lines: 11 def test_asfreq(): """Test asfreq method""" f_print_header("Test: asfreq") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: asfreq requires DatetimeIndex, may not work with RangeIndex try: result = df.asfreq('D') f_print_info(f"asfreq result shape: {result.shape}") f_print_success("asfreq: passed") except Exception: f_print_info("asfreq: skipped (requires DatetimeIndex)") return True except Exception as e: f_print_error(f"asfreq failed: {e}") return False .. _example-dataframe-at_time-113: .. dropdown:: at_time (test_df_phase6.py:392) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 382 :emphasize-lines: 11 def test_at_time(): """Test at_time method""" f_print_header("Test: at_time") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: at_time requires DatetimeIndex try: result = df.at_time('12:00') f_print_info(f"at_time result shape: {result.shape}") f_print_success("at_time: passed") except Exception: f_print_info("at_time: skipped (requires DatetimeIndex)") return True except Exception as e: f_print_error(f"at_time failed: {e}") return False .. _example-dataframe-between_time-114: .. dropdown:: between_time (test_df_phase6.py:414) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 404 :emphasize-lines: 11 def test_between_time(): """Test between_time method""" f_print_header("Test: between_time") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: between_time requires DatetimeIndex try: result = df.between_time('09:00', '17:00') f_print_info(f"between_time result shape: {result.shape}") f_print_success("between_time: passed") except Exception: f_print_info("between_time: skipped (requires DatetimeIndex)") return True except Exception as e: f_print_error(f"between_time failed: {e}") return False .. _example-dataframe-diff-115: .. dropdown:: diff (test_dataframe_phase3.py:383) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 373 :emphasize-lines: 11 # Difference and Change Tests # ============================================================================= def test_diff(): """Test diff() method""" f_print_header("Test: DataFrame.diff") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 4.0, 7.0]}) result = df.diff() ctx.assert_equal((4, 1), result.shape, "diff shape is (4, 1)") # Values should be [NaN, 1, 2, 3] f_print_success("DataFrame.diff: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-first_valid_index-116: .. dropdown:: first_valid_index (test_df_sorting_reshaping.py:388) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 378 :emphasize-lines: 11 return False def test_first_last_valid_index(): """Test first_valid_index and last_valid_index""" f_print_header("Test: first_valid_index / last_valid_index") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) first = df.first_valid_index() f_print_info(f"first_valid_index: {first}") last = df.last_valid_index() f_print_info(f"last_valid_index: {last}") f_print_success("first_valid_index/last_valid_index: passed") return True except Exception as e: f_print_error(f"first/last_valid_index failed: {e}") .. _example-dataframe-last_valid_index-117: .. dropdown:: last_valid_index (test_df_sorting_reshaping.py:391) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 381 :emphasize-lines: 11 def test_first_last_valid_index(): """Test first_valid_index and last_valid_index""" f_print_header("Test: first_valid_index / last_valid_index") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) first = df.first_valid_index() f_print_info(f"first_valid_index: {first}") last = df.last_valid_index() f_print_info(f"last_valid_index: {last}") f_print_success("first_valid_index/last_valid_index: passed") return True except Exception as e: f_print_error(f"first/last_valid_index failed: {e}") return False .. _example-dataframe-pct_change-118: .. dropdown:: pct_change (test_dataframe_phase3.py:402) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 392 :emphasize-lines: 11 return False def test_pct_change(): """Test pct_change() method""" f_print_header("Test: DataFrame.pct_change") try: df = pandasCore.DataFrame({'A': [10.0, 11.0, 12.1]}) result = df.pct_change() ctx.assert_equal((3, 1), result.shape, "pct_change shape is (3, 1)") # Values should be [NaN, 0.1, 0.1] f_print_success("DataFrame.pct_change: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-shift-119: .. dropdown:: shift (test_df_sorting_reshaping.py:335) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 325 :emphasize-lines: 11 def test_shift(): """Test shift method""" f_print_header("Test: shift") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Shift forward shifted = df.shift(1) f_print_info(f"Shifted (1) shape: {shifted.shape}") # Shift backward shifted_back = df.shift(-1) f_print_info(f"Shifted (-1) shape: {shifted_back.shape}") f_print_success("shift: passed") return True except Exception as e: .. _example-dataframe-to_period-120: .. dropdown:: to_period (test_df_phase6.py:304) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 294 :emphasize-lines: 11 def test_to_period(): """Test to_period method""" f_print_header("Test: to_period") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: to_period requires DatetimeIndex try: result = df.to_period('M') f_print_info(f"to_period result shape: {result.shape}") f_print_success("to_period: passed") except Exception: f_print_info("to_period: skipped (requires DatetimeIndex)") return True except Exception as e: f_print_error(f"to_period failed: {e}") return False .. _example-dataframe-to_timestamp-121: .. dropdown:: to_timestamp (test_df_phase6.py:326) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 316 :emphasize-lines: 11 def test_to_timestamp(): """Test to_timestamp method""" f_print_header("Test: to_timestamp") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: to_timestamp requires PeriodIndex try: result = df.to_timestamp() f_print_info(f"to_timestamp result shape: {result.shape}") f_print_success("to_timestamp: passed") except Exception: f_print_info("to_timestamp: skipped (requires PeriodIndex)") return True except Exception as e: f_print_error(f"to_timestamp failed: {e}") return False .. _example-dataframe-tz_convert-122: .. dropdown:: tz_convert (test_df_phase6.py:370) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 360 :emphasize-lines: 11 def test_tz_convert(): """Test tz_convert method""" f_print_header("Test: tz_convert") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: tz_convert requires tz-aware DatetimeIndex try: result = df.tz_convert('US/Eastern') f_print_info(f"tz_convert result shape: {result.shape}") f_print_success("tz_convert: passed") except Exception: f_print_info("tz_convert: skipped (requires tz-aware DatetimeIndex)") return True except Exception as e: f_print_error(f"tz_convert failed: {e}") return False .. _example-dataframe-tz_localize-123: .. dropdown:: tz_localize (test_df_phase6.py:348) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 338 :emphasize-lines: 11 def test_tz_localize(): """Test tz_localize method""" f_print_header("Test: tz_localize") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Note: tz_localize requires DatetimeIndex try: result = df.tz_localize('UTC') f_print_info(f"tz_localize result shape: {result.shape}") f_print_success("tz_localize: passed") except Exception: f_print_info("tz_localize: skipped (requires DatetimeIndex)") return True except Exception as e: f_print_error(f"tz_localize failed: {e}") return False .. _example-dataframe-to_csv-124: .. dropdown:: to_csv (test_dataframe_io.py:38) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 28 :emphasize-lines: 11 def test_to_csv(): """Test to_csv method""" f_print_header("Test: to_csv") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Test returning string (no file) csv_str = df.to_csv(index=False) if csv_str is not None and 'A' in csv_str and 'B' in csv_str: f_print_success("to_csv returns CSV string") else: f_print_error(f"to_csv returned unexpected result: {csv_str}") return False # Test with index csv_with_idx = df.to_csv(index=True) if csv_with_idx is not None: f_print_success("to_csv with index works") .. _example-dataframe-to_dict-125: .. dropdown:: to_dict (test_dataframe_io.py:197) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 187 :emphasize-lines: 11 def test_to_dict(): """Test to_dict method""" f_print_header("Test: to_dict") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # Test default orient='dict' d = df.to_dict() if isinstance(d, dict) and 'A' in d and 'B' in d: f_print_success(f"to_dict (orient='dict'): {d}") else: f_print_error(f"to_dict failed: {d}") return False # Test orient='list' d_list = df.to_dict('list') if isinstance(d_list, dict): f_print_success(f"to_dict (orient='list'): {d_list}") .. _example-dataframe-to_excel-126: .. dropdown:: to_excel (test_excel_classes.py:13) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 3 :emphasize-lines: 11 # Phase 77: Python bindings for Excel classes import pandasCore import os def test_excel_writer_basic(): """Test ExcelWriter basic usage""" path = "temp/test_writer.xlsx" writer = pandasCore.ExcelWriter(path) df = pandasCore.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) df.to_excel(writer, sheet_name="Data") writer.close() assert os.path.exists(path), "Excel file not created" os.remove(path) def test_excel_writer_context(): """Test ExcelWriter context manager""" path = "temp/test_ctx_writer.xlsx" with pandasCore.ExcelWriter(path) as writer: df = pandasCore.DataFrame({"X": [1, 2]}) df.to_excel(writer, sheet_name="Sheet1") .. _example-dataframe-to_hdf-127: .. dropdown:: to_hdf (test_hdf5_store.py:91) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 81 :emphasize-lines: 11 os.remove(path) def test_read_hdf(): """Test pandasCore.read_hdf()""" global tests_run tests_run += 1 path = "temp/test_read.h5" os.makedirs("temp", exist_ok=True) df = pandasCore.DataFrame({"A": [1, 2, 3]}) df.to_hdf(path, key="mykey") df2 = pandasCore.read_hdf(path, key="mykey") assert len(df2) == 3, f"Expected 3 rows, got {len(df2)}" os.remove(path) def test_to_hdf(): """Test DataFrame.to_hdf()""" global tests_run tests_run += 1 .. _example-dataframe-to_html-128: .. dropdown:: to_html (test_dataframe_io.py:123) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 113 :emphasize-lines: 11 def test_to_html(): """Test to_html method""" f_print_header("Test: to_html") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # Test returning string html_str = df.to_html() if html_str is not None and '' in xml_str: f_print_success("to_xml returns XML string") else: f_print_error(f"to_xml failed: {xml_str[:100] if xml_str else 'None'}") return False return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-astype-136: .. dropdown:: astype (test_df_sorting_reshaping.py:410) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 400 :emphasize-lines: 11 def test_astype(): """Test astype method""" f_print_header("Test: astype") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Convert to int64 int_df = df.astype('int64') f_print_info(f"astype('int64') shape: {int_df.shape}") # Convert to string str_df = df.astype('string') f_print_info(f"astype('string') shape: {str_df.shape}") # Convert specific columns mixed_df = df.astype({'A': 'int64', 'B': 'float64'}) f_print_info(f"astype(dict) shape: {mixed_df.shape}") .. _example-dataframe-bool-137: .. dropdown:: bool (test_missing_methods.py:66) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 56 :emphasize-lines: 11 assert result2.size == 2, f"Expected size 2, got {result2.size}" def test_dataframe_bool(): """Test DataFrame.bool (deprecated)""" global tests_run tests_run += 1 df = pandasCore.DataFrame({'A': [1.0]}) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") result = df.bool() assert result == True, f"Expected True, got {result}" def test_series_bool_float(): """Test Series.bool for float Series (deprecated)""" global tests_run tests_run += 1 s = pandasCore.Series([1.0]) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") .. _example-dataframe-convert_dtypes-138: .. dropdown:: convert_dtypes (test_df_sorting_reshaping.py:437) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 427 :emphasize-lines: 11 def test_convert_dtypes(): """Test convert_dtypes method""" f_print_header("Test: convert_dtypes") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Convert dtypes converted = df.convert_dtypes() f_print_info(f"convert_dtypes shape: {converted.shape}") f_print_success("convert_dtypes: passed") return True except Exception as e: f_print_error(f"convert_dtypes failed: {e}") return False .. _example-dataframe-copy-139: .. dropdown:: copy (test_dataframe.py:141) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 131 :emphasize-lines: 11 def test_dataframe_copy(): """Test copy() method""" f_print_header("Test: DataFrame.copy") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) # Test deep copy df_copy = df.copy(deep=True) ctx.assert_equal(df.shape, df_copy.shape, "Copy has same shape") ctx.assert_equal(list(df.columns), list(df_copy.columns), "Copy has same columns") f_print_success("DataFrame.copy: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-infer_objects-140: .. dropdown:: infer_objects (test_df_phase6.py:201) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 191 :emphasize-lines: 11 return False def test_infer_objects(): """Test infer_objects method""" f_print_header("Test: infer_objects") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.infer_objects() f_print_info(f"infer_objects shape: {result.shape}") f_print_success("infer_objects: passed") return True except Exception as e: f_print_error(f"infer_objects failed: {e}") return False .. _example-dataframe-items-141: .. dropdown:: items (test_dataframe.py:180) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 170 :emphasize-lines: 11 return False def test_dataframe_items(): """Test items() method""" f_print_header("Test: DataFrame.items") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) items = df.items() ctx.assert_equal(2, len(items), "items() returns 2 items") # Check that items are tuples of (name, values) for item in items: ctx.assert_true(isinstance(item, tuple), "Each item is a tuple") ctx.assert_true(len(item) == 2, "Each item has 2 elements") f_print_success("DataFrame.items: All checks passed") return True .. _example-dataframe-iterrows-142: .. dropdown:: iterrows (test_dataframe.py:203) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 193 :emphasize-lines: 11 return False def test_dataframe_iterrows(): """Test iterrows() method""" f_print_header("Test: DataFrame.iterrows") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) rows = df.iterrows() ctx.assert_equal(2, len(rows), "iterrows() returns 2 rows") # Check structure for idx, row in rows: ctx.assert_true(isinstance(row, dict), "Row is a dict") ctx.assert_true('A' in row and 'B' in row, "Row contains A and B") f_print_success("DataFrame.iterrows: All checks passed") return True .. _example-dataframe-itertuples-143: .. dropdown:: itertuples (test_dataframe.py:227) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 217 :emphasize-lines: 11 def test_dataframe_itertuples(): """Test itertuples() method""" f_print_header("Test: DataFrame.itertuples") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # With index tuples = df.itertuples(index=True) ctx.assert_equal(2, len(tuples), "itertuples() returns 2 tuples") ctx.assert_equal(3, len(tuples[0]), "Each tuple has 3 elements (index + 2 cols)") # Without index tuples_no_idx = df.itertuples(index=False) ctx.assert_equal(2, len(tuples_no_idx[0]), "Without index: 2 elements") f_print_success("DataFrame.itertuples: All checks passed") return True .. _example-dataframe-keys-144: .. dropdown:: keys (test_dataframe.py:161) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 151 :emphasize-lines: 11 return False def test_dataframe_keys(): """Test keys() method""" f_print_header("Test: DataFrame.keys") try: df = pandasCore.DataFrame({'A': [1.0], 'B': [2.0], 'C': [3.0]}) keys = df.keys() ctx.assert_true(len(keys) == 3, "keys() returns 3 keys") ctx.assert_true('A' in keys and 'B' in keys and 'C' in keys, "keys contains A, B, C") f_print_success("DataFrame.keys: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-drop_duplicates-145: .. dropdown:: drop_duplicates (test_dataframe_phase2.py:123) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 113 :emphasize-lines: 11 def test_drop_duplicates(): """Test drop_duplicates method""" f_print_header("Test: drop_duplicates") try: df = pandasCore.DataFrame({'A': [1.0, 1.0, 2.0, 2.0], 'B': [1.0, 1.0, 2.0, 3.0]}) # Drop duplicates result = df.drop_duplicates() ctx.assert_true(result.shape[0] < df.shape[0], "Fewer rows after drop_duplicates") f_print_success("drop_duplicates: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False def test_duplicated(): .. _example-dataframe-duplicated-146: .. dropdown:: duplicated (test_dataframe_phase2.py:140) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 130 :emphasize-lines: 11 return False def test_duplicated(): """Test duplicated method""" f_print_header("Test: duplicated") try: df = pandasCore.DataFrame({'A': [1.0, 1.0, 2.0], 'B': [1.0, 1.0, 2.0]}) dups = df.duplicated() ctx.assert_equal(3, len(dups), "Duplicated returns list of length 3") # First occurrence should not be marked as duplicate ctx.assert_equal(False, dups[0], "First row is not duplicate") # Second row is duplicate of first ctx.assert_equal(True, dups[1], "Second row is duplicate") f_print_success("duplicated: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-isin-147: .. dropdown:: isin (test_dataframe_phase2.py:309) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 299 :emphasize-lines: 11 return False def test_isin(): """Test isin method""" f_print_header("Test: isin") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.isin([1.0, 5.0]) # isin returns list of rows: result[row][col] ctx.assert_equal(True, result[0][0], "1.0 is in values") ctx.assert_equal(True, result[1][1], "5.0 is in values") ctx.assert_equal(False, result[0][1], "4.0 is not in values") f_print_success("isin: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-round-148: .. dropdown:: round (test_dataframe_phase4.py:453) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 443 :emphasize-lines: 11 def test_round(): """Test round operation""" f_print_header("Test: round") try: df = pandasCore.DataFrame({'A': [1.234, 2.567, 3.891]}) # Round to 2 decimals result = df.round(2) col_a = result['A'] ctx.assert_close(1.23, col_a[0], "round(2): A[0] = 1.23") ctx.assert_close(2.57, col_a[1], "round(2): A[1] = 2.57") ctx.assert_close(3.89, col_a[2], "round(2): A[2] = 3.89") # Round to 0 decimals result0 = df.round(0) col_a0 = result0['A'] ctx.assert_close(1.0, col_a0[0], "round(0): A[0] = 1.0") ctx.assert_close(3.0, col_a0[1], "round(0): A[1] = 3.0") .. _example-dataframe-abs-149: .. dropdown:: abs (test_dataframe_phase4.py:431) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 421 :emphasize-lines: 11 # ============================================================================= # Utility Methods Tests # ============================================================================= def test_abs(): """Test abs operation""" f_print_header("Test: abs") try: df = pandasCore.DataFrame({'A': [-1.0, 2.0, -3.0], 'B': [4.0, -5.0, 6.0]}) result = df.abs() col_a = result['A'] ctx.assert_close(1.0, col_a[0], "abs: A[0] = 1.0") ctx.assert_close(2.0, col_a[1], "abs: A[1] = 2.0") ctx.assert_close(3.0, col_a[2], "abs: A[2] = 3.0") f_print_success("abs: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-add_prefix-150: .. dropdown:: add_prefix (test_dataframe_phase2.py:42) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 32 :emphasize-lines: 11 # ============================================================================= # Test Functions # ============================================================================= def test_add_prefix(): """Test add_prefix method""" f_print_header("Test: add_prefix") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) result = df.add_prefix("col_") cols = list(result.columns) ctx.assert_true('col_A' in cols, "Column 'col_A' exists") ctx.assert_true('col_B' in cols, "Column 'col_B' exists") ctx.assert_equal(2, len(cols), "Two columns after prefix") f_print_success("add_prefix: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") .. _example-dataframe-add_suffix-151: .. dropdown:: add_suffix (test_dataframe_phase2.py:62) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 52 :emphasize-lines: 11 f_print_error(f"Exception: {e}") return False def test_add_suffix(): """Test add_suffix method""" f_print_header("Test: add_suffix") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) result = df.add_suffix("_col") cols = list(result.columns) ctx.assert_true('A_col' in cols, "Column 'A_col' exists") ctx.assert_true('B_col' in cols, "Column 'B_col' exists") f_print_success("add_suffix: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-all-152: .. dropdown:: all (test_dataframe_phase3.py:611) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 601 :emphasize-lines: 11 # Boolean Reduction Tests # ============================================================================= def test_all(): """Test all() method""" f_print_header("Test: DataFrame.all") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [0.0, 1.0, 2.0]}) result = df.all() ctx.assert_true(result['A'] == True, "all A = True (all non-zero)") ctx.assert_true(result['B'] == False, "all B = False (has zero)") f_print_success("DataFrame.all: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-any-153: .. dropdown:: any (test_dataframe_phase3.py:630) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 620 :emphasize-lines: 11 return False def test_any(): """Test any() method""" f_print_header("Test: DataFrame.any") try: df = pandasCore.DataFrame({'A': [0.0, 0.0, 0.0], 'B': [0.0, 1.0, 0.0]}) result = df.any() ctx.assert_true(result['A'] == False, "any A = False (all zero)") ctx.assert_true(result['B'] == True, "any B = True (has non-zero)") f_print_success("DataFrame.any: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-boxplot-154: .. dropdown:: boxplot (test_signature_phase13.py:262) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 252 :emphasize-lines: 11 except RuntimeError as e: assert "Not implemented" in str(e) def test_boxplot_signature(): """Test DataFrame.boxplot has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) try: result = df.boxplot(column=None, by=None, ax=None, fontsize=None, rot=0, grid=True, figsize=None, layout=None, return_type=None, backend=None) except RuntimeError as e: assert "Not implemented" in str(e) def test_from_dict_signature(): """Test DataFrame.from_dict has all pandas parameters.""" import pandasCore data = {'A': [1.0, 2.0], 'B': [3.0, 4.0]} .. _example-dataframe-clip-155: .. dropdown:: clip (test_dataframe_phase4.py:480) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 470 :emphasize-lines: 11 f_print_error(f"Exception: {e}") return False def test_clip(): """Test clip operation""" f_print_header("Test: clip") try: df = pandasCore.DataFrame({'A': [1.0, 5.0, 10.0, 15.0, 20.0]}) result = df.clip(lower=5.0, upper=15.0) col_a = result['A'] ctx.assert_close(5.0, col_a[0], "clip: A[0] clipped to 5.0") ctx.assert_close(5.0, col_a[1], "clip: A[1] = 5.0") ctx.assert_close(10.0, col_a[2], "clip: A[2] = 10.0") ctx.assert_close(15.0, col_a[3], "clip: A[3] = 15.0") ctx.assert_close(15.0, col_a[4], "clip: A[4] clipped to 15.0") f_print_success("clip: All tests passed") return True .. _example-dataframe-corr-156: .. dropdown:: corr (test_dataframe_phase3.py:425) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 415 :emphasize-lines: 11 # Correlation and Covariance Tests # ============================================================================= def test_corr(): """Test corr() method""" f_print_header("Test: DataFrame.corr") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [1.0, 2.0, 3.0]}) result = df.corr() ctx.assert_equal((2, 2), result.shape, "corr shape is (2, 2)") f_print_success("DataFrame.corr: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-cov-157: .. dropdown:: cov (test_dataframe_phase3.py:443) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 433 :emphasize-lines: 11 return False def test_cov(): """Test cov() method""" f_print_header("Test: DataFrame.cov") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) result = df.cov() ctx.assert_equal((2, 2), result.shape, "cov shape is (2, 2)") f_print_success("DataFrame.cov: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-divide-158: .. dropdown:: divide (test_dataframe_phase4.py:388) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 378 :emphasize-lines: 11 f_print_error(f"Exception: {e}") return False def test_divide(): """Test divide alias""" f_print_header("Test: divide") try: df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0]}) result = df.divide(10.0) col_a = result['A'] ctx.assert_close(1.0, col_a[0], "divide scalar: A[0] = 1.0") f_print_success("divide: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-eval-159: .. dropdown:: eval (test_dataframe_phase2.py:348) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 338 :emphasize-lines: 11 def test_eval(): """Test eval method""" f_print_header("Test: eval") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Test expression evaluation (returns list) result = df.eval("A + B") ctx.assert_equal(3, len(result), "eval returns 3 values") ctx.assert_close(5.0, result[0], "First value is 1+4=5") # Test assignment (returns DataFrame) df2 = df.eval("C = A + B") ctx.assert_true('C' in list(df2.columns), "Column C created by eval") f_print_success("eval: All checks passed") return True except Exception as e: .. _example-dataframe-filter-160: .. dropdown:: filter (test_df_sorting_reshaping.py:362) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 352 :emphasize-lines: 11 f_print_header("Test: filter") try: df = pandasCore.DataFrame({ 'A_col': [1.0, 2.0], 'B_col': [3.0, 4.0], 'C_data': [5.0, 6.0] }) # Filter by items filtered = df.filter(items=['A_col', 'B_col']) f_print_info(f"Filtered (items) shape: {filtered.shape}") # Filter by like filtered_like = df.filter(like='col') f_print_info(f"Filtered (like 'col') shape: {filtered_like.shape}") # Filter by regex filtered_regex = df.filter(regex='.*col') f_print_info(f"Filtered (regex) shape: {filtered_regex.shape}") .. _example-dataframe-hist-161: .. dropdown:: hist (test_signature_phase13.py:249) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 239 :emphasize-lines: 11 assert isinstance(result, str) def test_hist_signature(): """Test DataFrame.hist has all pandas parameters.""" import pandasCore df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # Note: binding requires data as first positional arg try: result = df.hist(df, column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None, ax=None, sharex=False, sharey=False, figsize=None, layout=None, bins=10, backend=None, legend=False) except RuntimeError as e: assert "Not implemented" in str(e) def test_boxplot_signature(): """Test DataFrame.boxplot has all pandas parameters.""" import pandasCore .. _example-dataframe-info-162: .. dropdown:: info (test_dataframe.py:279) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 269 :emphasize-lines: 11 def test_dataframe_info(): """Test info() method""" f_print_header("Test: DataFrame.info") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) # info() prints to stdout, so we just test it doesn't raise f_print_info("Calling df.info():") df.info() f_print_success("DataFrame.info: No exceptions raised") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-memory_usage-163: .. dropdown:: memory_usage (test_dataframe.py:297) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 287 :emphasize-lines: 11 return False def test_dataframe_memory_usage(): """Test memory_usage() method""" f_print_header("Test: DataFrame.memory_usage") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [4.0, 5.0, 6.0]}) mem = df.memory_usage() ctx.assert_true(isinstance(mem, dict), "memory_usage returns dict") ctx.assert_true(len(mem) > 0, "memory_usage has entries") # Check values are positive for col, usage in mem.items(): ctx.assert_true(usage >= 0, f"Memory usage for {col} is non-negative") f_print_success("DataFrame.memory_usage: All checks passed") return True .. _example-dataframe-multiply-164: .. dropdown:: multiply (test_dataframe_phase4.py:370) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 360 :emphasize-lines: 11 f_print_error(f"Exception: {e}") return False def test_multiply(): """Test multiply alias""" f_print_header("Test: multiply") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0]}) result = df.multiply(3.0) col_a = result['A'] ctx.assert_close(3.0, col_a[0], "multiply scalar: A[0] = 3.0") f_print_success("multiply: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-product-165: .. dropdown:: product (test_dataframe_phase4.py:406) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 396 :emphasize-lines: 11 f_print_error(f"Exception: {e}") return False def test_product(): """Test product alias for prod""" f_print_header("Test: product") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0], 'B': [2.0, 3.0, 4.0]}) result = df.product() # Product of column A: 1*2*3 = 6 # Product of column B: 2*3*4 = 24 ctx.assert_close(6.0, result['A'], "product: A = 6.0") ctx.assert_close(24.0, result['B'], "product: B = 24.0") f_print_success("product: All tests passed") return True except Exception as e: .. _example-dataframe-select_dtypes-166: .. dropdown:: select_dtypes (test_dataframe_phase2.py:452) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 442 :emphasize-lines: 11 def test_select_dtypes(): """Test select_dtypes method""" f_print_header("Test: select_dtypes") try: df = pandasCore.DataFrame({'A': [1.0, 2.0], 'B': [3.0, 4.0]}) # Select numeric types (all columns are float64) result = df.select_dtypes(include=['number']) ctx.assert_true(result.ncols >= 0, "select_dtypes returns DataFrame") f_print_success("select_dtypes: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False def test_rename_axis(): .. _example-dataframe-set_flags-167: .. dropdown:: set_flags (test_dataframe.py:383) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 373 :emphasize-lines: 11 def test_dataframe_set_flags(): """Test set_flags() method""" f_print_header("Test: DataFrame.set_flags") try: df = pandasCore.DataFrame({'A': [1.0, 2.0]}) # set_flags returns a copy (placeholder implementation) df_flagged = df.set_flags(allows_duplicate_labels=True) ctx.assert_equal(df.shape, df_flagged.shape, "set_flags returns same shape") f_print_success("DataFrame.set_flags: All checks passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-subtract-168: .. dropdown:: subtract (test_dataframe_phase4.py:352) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 342 :emphasize-lines: 11 # ============================================================================= # Arithmetic Aliases Tests # ============================================================================= def test_subtract(): """Test subtract alias""" f_print_header("Test: subtract") try: df = pandasCore.DataFrame({'A': [10.0, 20.0, 30.0]}) result = df.subtract(5.0) col_a = result['A'] ctx.assert_close(5.0, col_a[0], "subtract scalar: A[0] = 5.0") f_print_success("subtract: All tests passed") return True except Exception as e: f_print_error(f"Exception: {e}") return False .. _example-dataframe-truncate-169: .. dropdown:: truncate (test_df_sorting_reshaping.py:501) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 491 :emphasize-lines: 11 def test_truncate(): """Test truncate method""" f_print_header("Test: truncate") try: df = pandasCore.DataFrame({'A': [1.0, 2.0, 3.0, 4.0, 5.0]}) # Truncate (simplified - may not work with string indices) try: truncated = df.truncate(before='1', after='3') f_print_info(f"truncate shape: {truncated.shape}") except Exception as e: f_print_info(f"truncate: {e}") f_print_success("truncate: passed") return True except Exception as e: f_print_error(f"truncate failed: {e}") return False