Series ====== .. currentmodule:: pandasCore .. class:: Series One-dimensional labeled array capable of holding any data type. Example ------- .. code-block:: python import pandasCore as pd # Create Series s = pd.Series([1.0, 2.0, 3.0], name='values') print(s.size) # 3 print(s.dtype) # float64 Attributes ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Attribute - Description - Example * - :attr:`~Series.T` - Return the transpose (self for Series) - :ref:`View ` * - :attr:`~Series.at` - Access a single value for a row label. Returns dict for lookup. - :ref:`View ` * - :attr:`~Series.cat` - Accessor object for categorical properties. - :ref:`View ` * - :attr:`~Series.dt` - Accessor object for datetimelike properties. - :ref:`View ` * - :attr:`~Series.dtype` - Return the dtype object of the underlying data - :ref:`View ` * - :attr:`~Series.empty` - Indicator whether Series is empty - * - :attr:`~Series.iat` - Access a single value by integer position. Returns list for lookup. - :ref:`View ` * - :attr:`~Series.iloc` - Purely integer-location based indexing. Returns list for indexing. - :ref:`View ` * - :attr:`~Series.index` - The index (axis labels) of the Series - :ref:`View ` * - :attr:`~Series.loc` - Access a group of rows by label(s). Returns dict of {label: value} ... - :ref:`View ` * - :attr:`~Series.name` - Return the name of the Series - :ref:`View ` * - :attr:`~Series.nbytes` - Return the number of bytes in the underlying data - :ref:`View ` * - :attr:`~Series.ndim` - Number of dimensions of the underlying data (always 1 for Series) - :ref:`View ` * - :attr:`~Series.plot` - Accessor for plot methods (requires matplotlib) - :ref:`View ` * - :attr:`~Series.shape` - Return a tuple of the shape of the underlying data - :ref:`View ` * - :attr:`~Series.size` - Return the number of elements in the underlying data - :ref:`View ` * - :attr:`~Series.sparse` - Accessor for sparse data operations. - :ref:`View ` * - :attr:`~Series.str` - Vectorized string functions for Series. - :ref:`View ` Construction ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.__init__` ``(data: object = None, index: object = None, dtype: object = None, name: object = None, copy: object = None, fastpath: object = None)`` - Create a Series from data. - :ref:`View ` Indexing / Selection -------------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.__getitem__` ``(key: typing.SupportsInt)`` - Get element by position - * - :meth:`~Series.__setitem__` ``(key: typing.SupportsInt, value: typing.SupportsFloat)`` - Set element by position - * - :meth:`~Series.first` ``(offset: str)`` - Select initial periods of time series data based on a date offset. - :ref:`View ` * - :meth:`~Series.get` ``(key: str, default: object = None)`` - Get item from object for given key (ex: DataFrame column). - :ref:`View ` * - :meth:`~Series.head` ``(n: typing.SupportsInt = 5)`` - Return the first n elements - :ref:`View ` * - :meth:`~Series.idxmax` ``(axis: typing.SupportsInt = 0, skipna: bool = True, *args, **kwargs)`` - Return the index of the maximum value. - :ref:`View ` * - :meth:`~Series.idxmin` ``(axis: typing.SupportsInt = 0, skipna: bool = True, *args, **kwargs)`` - Return the index of the minimum value. - :ref:`View ` * - :meth:`~Series.last` ``(offset: str)`` - Select final periods of time series data based on a date offset. - :ref:`View ` * - :meth:`~Series.mask` ``(cond: collections.abc.Sequence[bool], other: object = None, *, inplace: bool = False, axis: object = None, level: object = None)`` - Replace values where the condition is True. - :ref:`View ` * - :meth:`~Series.nlargest` ``(n: typing.SupportsInt = 5, keep: str = 'first')`` - Return the largest n elements. - :ref:`View ` * - :meth:`~Series.nsmallest` ``(n: typing.SupportsInt = 5, keep: str = 'first')`` - Return the smallest n elements. - :ref:`View ` * - :meth:`~Series.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:`~Series.tail` ``(n: typing.SupportsInt = 5)`` - Return the last n elements - :ref:`View ` * - :meth:`~Series.take` ``(indices: collections.abc.Sequence[typing.SupportsInt], axis: typing.SupportsInt = 0, **kwargs)`` - Return the elements in the given positional indices along an axis. - :ref:`View ` * - :meth:`~Series.where` ``(cond: collections.abc.Sequence[bool], other: typing.SupportsFloat = nan, *, inplace: bool = False, axis: object = None, level: object = None)`` - Replace values where the condition is False. - :ref:`View ` * - :meth:`~Series.xs` ``(key: str, axis: typing.SupportsInt = 0, level: object = None, drop_level: bool = True)`` - Return cross-section from the Series. - :ref:`View ` Data Manipulation ----------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.drop` ``(labels: object = None, *, axis: typing.SupportsInt = 0, index: object = None, columns: object = None, level: object = None, inplace: bool = False, errors: str = 'raise')`` - Return Series with specified index labels removed. - :ref:`View ` * - :meth:`~Series.droplevel` ``(level: typing.SupportsInt, axis: typing.SupportsInt = 0)`` - Return Series with requested index level removed. - :ref:`View ` * - :meth:`~Series.pop` ``(item: str)`` - Return item and drops from series. - :ref:`View ` * - :meth:`~Series.reindex` ``(index: object = None, *, axis: object = None, method: object = None, copy: object = None, level: object = None, fill_value: object = None, limit: object = None, tolerance: object = None)`` - Conform Series to new index with optional filling logic. - :ref:`View ` * - :meth:`~Series.rename` ``(index: object = None, *, axis: object = None, copy: object = None, inplace: bool = False, level: object = None, errors: str = 'ignore')`` - Alter Series name or index labels. - :ref:`View ` * - :meth:`~Series.rename_axis` ``(mapper: object = None, *, index: object = None, axis: typing.SupportsInt = 0, copy: bool = True, inplace: bool = False)`` - Set the name of the axis (index). - :ref:`View ` * - :meth:`~Series.reorder_levels` ``(order: collections.abc.Sequence[typing.SupportsInt])`` - Rearrange index levels using input order. - :ref:`View ` * - :meth:`~Series.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:`~Series.reset_index` ``(level: object = None, *, drop: bool = False, name: object = None, inplace: bool = False, allow_duplicates: bool = False)`` - Reset the index. - :ref:`View ` * - :meth:`~Series.set_axis` ``(labels: collections.abc.Sequence[str], *, axis: typing.SupportsInt = 0, copy: object = None)`` - Assign desired index to given axis. - :ref:`View ` * - :meth:`~Series.swaplevel` ``(i: typing.SupportsInt = -2, j: typing.SupportsInt = -1, copy: object = None)`` - Swap levels i and j in a MultiIndex. - :ref:`View ` * - :meth:`~Series.update` ``(other: pandasCore.Series)`` - Modify Series in place using values from another Series. - Missing Data ------------ .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.backfill` ``(*, axis: object = None, inplace: bool = False, limit: object = None, downcast: object = None)`` - Alias for bfill. Fill NA/NaN values by using the next valid observa... - :ref:`View ` * - :meth:`~Series.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. - :ref:`View ` * - :meth:`~Series.dropna` ``(*, axis: typing.SupportsInt = 0, inplace: bool = False, how: object = None, ignore_index: bool = False)`` - Return a new Series with missing values removed. - :ref:`View ` * - :meth:`~Series.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:`~Series.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:`~Series.interpolate` ``(method: str = 'linear', *, axis: typing.SupportsInt = 0, limit: object = None, inplace: bool = False, limit_direction: object = None, limit_area: object = None, downcast: object = None, **kwargs)`` - Fill NaN values using interpolation. - :ref:`View ` * - :meth:`~Series.isna` ``()`` - Detect missing values. - :ref:`View ` * - :meth:`~Series.isnull` ``()`` - Alias for isna. Detect missing values. - :ref:`View ` * - :meth:`~Series.notna` ``()`` - Detect existing (non-missing) values. - :ref:`View ` * - :meth:`~Series.notnull` ``()`` - Alias for notna. Detect non-missing values. - :ref:`View ` * - :meth:`~Series.pad` ``(*, axis: object = None, inplace: bool = False, limit: object = None, downcast: object = None)`` - Alias for ffill. Fill NA/NaN values by propagating the last valid o... - :ref:`View ` Statistics ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.count` ``()`` - Return number of non-NA/null observations in the Series. - :ref:`View ` * - :meth:`~Series.cummax` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative maximum over a DataFrame or Series axis. - :ref:`View ` * - :meth:`~Series.cummin` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative minimum over a DataFrame or Series axis. - :ref:`View ` * - :meth:`~Series.cumprod` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative product over a DataFrame or Series axis. - :ref:`View ` * - :meth:`~Series.cumsum` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return cumulative sum over a DataFrame or Series axis. - :ref:`View ` * - :meth:`~Series.describe` ``(percentiles: object = None, include: object = None, exclude: object = None)`` - Generate descriptive statistics. - :ref:`View ` * - :meth:`~Series.kurt` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return unbiased kurtosis over requested axis. - :ref:`View ` * - :meth:`~Series.kurtosis` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return unbiased kurtosis over requested axis. Alias for kurt. - :ref:`View ` * - :meth:`~Series.max` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the maximum of the values over the requested axis. - :ref:`View ` * - :meth:`~Series.mean` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the mean of the values over the requested axis. - :ref:`View ` * - :meth:`~Series.median` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the median of the values over the requested axis. - :ref:`View ` * - :meth:`~Series.min` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return the minimum of the values over the requested axis. - :ref:`View ` * - :meth:`~Series.mode` ``(dropna: bool = True)`` - Return the mode(s) of the Series. - :ref:`View ` * - :meth:`~Series.nunique` ``(dropna: bool = True)`` - Return number of unique elements. - :ref:`View ` * - :meth:`~Series.prod` ``(axis: object = None, 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:`~Series.quantile` ``(q: typing.SupportsFloat = 0.5, interpolation: str = 'linear')`` - Return value at the given quantile. - :ref:`View ` * - :meth:`~Series.sem` ``(axis: object = None, 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:`~Series.skew` ``(axis: object = 0, skipna: bool = True, numeric_only: bool = False, **kwargs)`` - Return unbiased skew over requested axis. - :ref:`View ` * - :meth:`~Series.std` ``(axis: object = None, skipna: bool = True, ddof: typing.SupportsInt = 1, numeric_only: bool = False, **kwargs)`` - Return sample standard deviation over requested axis. - :ref:`View ` * - :meth:`~Series.sum` ``(axis: object = None, 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:`~Series.value_counts` ``(normalize: bool = False, sort: bool = True, ascending: bool = False, bins: object = None, dropna: bool = True)`` - Return a Series containing counts of unique values. - :ref:`View ` * - :meth:`~Series.var` ``(axis: object = None, 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:`~Series.agg` ``(func: object = None, axis: typing.SupportsInt = 0, *args, **kwargs)`` - Aggregate using one or more operations over the specified axis. - :ref:`View ` * - :meth:`~Series.aggregate` ``(func: object = None, axis: typing.SupportsInt = 0, *args, **kwargs)`` - Aggregate using one or more operations over the specified axis. Ali... - :ref:`View ` * - :meth:`~Series.apply` ``(func: object, convert_dtype: object = None, args: object = (), *, by_row: object = 'compat', **kwargs)`` - Invoke function on values of Series. - :ref:`View ` * - :meth:`~Series.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:`~Series.expanding` ``(min_periods: typing.SupportsInt = 1, axis: object = None, method: str = 'single')`` - Provide expanding window calculations. - :ref:`View ` * - :meth:`~Series.groupby` ``(by: object = None, axis: typing.SupportsInt = 0, level: object = None, as_index: bool = True, sort: bool = True, group_keys: bool = True, observed: object = None, dropna: bool = True)`` - Group Series using a mapper or by a Series of columns. - :ref:`View ` * - :meth:`~Series.map` ``(arg: object, na_action: object = None)`` - Map values of Series according to an input mapping or function. - :ref:`View ` * - :meth:`~Series.pipe` ``(func: object, *args, **kwargs)`` - Apply chainable functions that expect Series. - :ref:`View ` * - :meth:`~Series.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:`~Series.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:`~Series.transform` ``(func: object, axis: typing.SupportsInt = 0, *args, **kwargs)`` - Call func on self producing a Series with the same axis shape as self. - :ref:`View ` Arithmetic ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.add` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Addition of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.div` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Floating division of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.dot` ``(other: object)`` - Compute the dot product between the Series and another. - * - :meth:`~Series.floordiv` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Integer division of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.mod` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Modulo of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.mul` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Multiplication of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.pow` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Exponential power of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.radd` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse addition of series and other, element-wise (other + ... - :ref:`View ` * - :meth:`~Series.rdiv` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse division of series and other, element-wise (other / ... - :ref:`View ` * - :meth:`~Series.rfloordiv` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse integer division of series and other, element-wise (... - :ref:`View ` * - :meth:`~Series.rmod` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse modulo of series and other, element-wise (other % se... - :ref:`View ` * - :meth:`~Series.rmul` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse multiplication of series and other, element-wise (ot... - :ref:`View ` * - :meth:`~Series.rpow` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse power of series and other, element-wise (other ** se... - :ref:`View ` * - :meth:`~Series.rsub` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse subtraction of series and other, element-wise (other... - :ref:`View ` * - :meth:`~Series.rtruediv` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Reverse true division of series and other, element-wise (oth... - * - :meth:`~Series.sub` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Subtraction of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.truediv` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return True division of series and other, element-wise. - :ref:`View ` Comparison ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.__eq__` ``(self, value, /)`` - Return self==value. - * - :meth:`~Series.__ge__` ``(arg0: object)`` - - * - :meth:`~Series.__gt__` ``(arg0: object)`` - - * - :meth:`~Series.__le__` ``(arg0: object)`` - - * - :meth:`~Series.__lt__` ``(arg0: object)`` - - * - :meth:`~Series.__ne__` ``(self, value, /)`` - Return self!=value. - * - :meth:`~Series.compare` ``(other: pandasCore.Series, align_axis: typing.SupportsInt = 1, keep_shape: bool = False, keep_equal: bool = False, result_names: tuple[str, str] = ('self', 'other'))`` - Compare to another Series and show the differences. - * - :meth:`~Series.eq` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Equal to of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.equals` ``(other: pandasCore.Series)`` - Test whether two objects contain the same elements. - * - :meth:`~Series.ge` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Greater than or equal to of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.gt` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Greater than of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.le` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Less than or equal to of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.lt` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Less than of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.ne` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Not equal to of series and other, element-wise. - :ref:`View ` Sorting ------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.argsort` ``(axis: typing.SupportsInt = 0, kind: str = 'quicksort', order: object = None, stable: object = None)`` - Return the integer indices that would sort the Series values. - :ref:`View ` * - :meth:`~Series.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:`~Series.searchsorted` ``(value: typing.SupportsFloat, side: str = 'left', sorter: object = None)`` - Find indices where elements should be inserted to maintain order. - :ref:`View ` * - :meth:`~Series.sort_index` ``(*, axis: typing.SupportsInt = 0, level: object = None, ascending: bool = 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:`~Series.sort_values` ``(*, axis: typing.SupportsInt = 0, ascending: bool = True, inplace: bool = False, kind: str = 'quicksort', na_position: str = 'last', ignore_index: bool = False, key: object = None)`` - Sort by the values. - :ref:`View ` Reshaping --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.explode` ``(ignore_index: bool = False)`` - Transform each element of a list-like to a row. - :ref:`View ` * - :meth:`~Series.squeeze` ``(axis: object = None)`` - Squeeze 1 dimensional axis objects into scalars. - * - :meth:`~Series.swapaxes` ``(axis1: typing.SupportsInt, axis2: typing.SupportsInt, copy: object = None)`` - Interchange axes and swap values axes appropriately. - :ref:`View ` * - :meth:`~Series.to_frame` ``(name: object = None)`` - Convert Series to DataFrame. - :ref:`View ` * - :meth:`~Series.transpose` ``(*args, **kwargs)`` - Return the transpose, which is by definition self. - :ref:`View ` * - :meth:`~Series.unstack` ``(level: object = -1, fill_value: object = None, sort: bool = True)`` - Unstack, also known as pivot, Series with MultiIndex to produce Dat... - :ref:`View ` Combining --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.align` ``(other: pandasCore.Series, 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 objects on their axes with the specified join method. - * - :meth:`~Series.combine` ``(other: pandasCore.Series, func: collections.abc.Callable, fill_value: object = None)`` - Combine the Series with another Series. - * - :meth:`~Series.combine_first` ``(other: pandasCore.Series)`` - Update null elements with value in the same location in other. - Time Series ----------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.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:`~Series.asof` ``(where: object, subset: object = None)`` - Return the last row(s) without any NaNs before where. - :ref:`View ` * - :meth:`~Series.at_time` ``(time: str, asof: bool = False, axis: object = None)`` - Select values at particular time of day (e.g., 9:30AM). - :ref:`View ` * - :meth:`~Series.between_time` ``(start_time: str, end_time: str, inclusive: str = 'both', axis: object = None)`` - Select values between particular times of the day. - :ref:`View ` * - :meth:`~Series.diff` ``(periods: typing.SupportsInt = 1)`` - First discrete difference of element. - :ref:`View ` * - :meth:`~Series.first_valid_index` ``()`` - Return index for first non-NA value or None, if no non-NA value is ... - :ref:`View ` * - :meth:`~Series.last_valid_index` ``()`` - Return index for last non-NA value or None, if no non-NA value is f... - :ref:`View ` * - :meth:`~Series.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:`~Series.shift` ``(periods: typing.SupportsInt = 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:`~Series.to_period` ``(freq: object = None, copy: object = None)`` - Convert Series from DatetimeIndex to PeriodIndex. - :ref:`View ` * - :meth:`~Series.to_timestamp` ``(freq: object = None, how: str = 'start', copy: object = None)`` - Cast to DatetimeIndex of timestamps. - :ref:`View ` * - :meth:`~Series.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:`~Series.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 Series to target time zone. - :ref:`View ` I/O --- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.to_clipboard` ``(*, excel: bool = True, sep: object = None, **kwargs)`` - Copy object to the system clipboard. - * - :meth:`~Series.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:`~Series.to_dict` ``(*, into: object = None)`` - Convert Series to dict. - :ref:`View ` * - :meth:`~Series.to_excel` ``(excel_writer: object, *, sheet_name: str = 'Sheet1', na_rep: str = '', float_format: object = None, columns: object = None, header: object = 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. - * - :meth:`~Series.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. - * - :meth:`~Series.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:`~Series.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 table. - :ref:`View ` * - :meth:`~Series.to_list` ``()`` - Return a list of the values - :ref:`View ` * - :meth:`~Series.to_markdown` ``(buf: object = None, mode: str = 'wt', index: bool = True, storage_options: object = None, **kwargs)`` - Print Series in Markdown-friendly format. - :ref:`View ` * - :meth:`~Series.to_numpy` ``(dtype: object = None, copy: bool = False, na_value: object = None, **kwargs)`` - A NumPy ndarray representing the values in this Series. - :ref:`View ` * - :meth:`~Series.to_pickle` ``(path: str, *, compression: str = 'infer', protocol: typing.SupportsInt = 5, storage_options: object = None)`` - Pickle (serialize) object to file. - * - :meth:`~Series.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. - * - :meth:`~Series.to_string` ``(buf: object = None, na_rep: str = 'NaN', float_format: object = None, header: bool = True, index: bool = True, length: bool = False, dtype: bool = False, name: bool = False, max_rows: object = None, min_rows: object = None)`` - Render a string representation of the Series. - :ref:`View ` * - :meth:`~Series.to_xarray` ``()`` - Return an xarray object from the pandas object. - * - :meth:`~Series.tolist` ``()`` - Return a list of the values (alias for to_list) - :ref:`View ` Conversion ---------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.astype` ``(dtype: str, copy: object = None, errors: str = 'raise')`` - Cast a pandas object to a specified dtype. - :ref:`View ` * - :meth:`~Series.bool` ``()`` - Return the bool of a single element Series. - :ref:`View ` * - :meth:`~Series.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:`~Series.copy` ``(deep: bool = True)`` - Make a copy of this object's indices and data. - :ref:`View ` * - :meth:`~Series.infer_objects` ``(copy: object = None)`` - Attempt to infer better dtypes for object columns. - :ref:`View ` * - :meth:`~Series.view` ``(dtype: object = None)`` - Create a new view of the Series. - :ref:`View ` Iteration --------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.__contains__` ``(item: typing.SupportsFloat)`` - Return True if value is in Series - * - :meth:`~Series.__iter__` ``()`` - Iterate over values - * - :meth:`~Series.__len__` ``()`` - Return the number of elements - * - :meth:`~Series.items` ``()`` - Lazily iterate over (index, value) tuples. - :ref:`View ` * - :meth:`~Series.keys` ``()`` - Return alias for index. - :ref:`View ` Set Operations -------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.drop_duplicates` ``(*, keep: str = 'first', inplace: bool = False, ignore_index: bool = False)`` - Return Series with duplicate values removed. - :ref:`View ` * - :meth:`~Series.duplicated` ``(keep: str = 'first')`` - Indicate duplicate Series values. - :ref:`View ` * - :meth:`~Series.isin` ``(values: collections.abc.Sequence[typing.SupportsFloat])`` - Check whether each element is in values. - :ref:`View ` * - :meth:`~Series.unique` ``()`` - Return unique values of Series. - :ref:`View ` Datetime Methods ---------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.round` ``(decimals: typing.SupportsInt = 0, *args, **kwargs)`` - Round each value to the given number of decimals. - :ref:`View ` Other Methods ------------- .. list-table:: :widths: 25 60 15 :header-rows: 1 * - Method - Description - Example * - :meth:`~Series.__hash__` ``(self, /)`` - Return hash(self). - * - :meth:`~Series.__repr__` ``()`` - - * - :meth:`~Series.__str__` ``()`` - - * - :meth:`~Series.abs` ``()`` - Return a Series with absolute numeric value of each element. - :ref:`View ` * - :meth:`~Series.add_prefix` ``(prefix: str, axis: object = None)`` - Prefix labels with string prefix. - :ref:`View ` * - :meth:`~Series.add_suffix` ``(suffix: str, axis: object = None)`` - Suffix labels with string suffix. - :ref:`View ` * - :meth:`~Series.all` ``(axis: object = 0, bool_only: bool = False, skipna: bool = True, **kwargs)`` - Return whether all elements are True, potentially over an axis. - :ref:`View ` * - :meth:`~Series.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:`~Series.argmax` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return int position of the maximum value. - :ref:`View ` * - :meth:`~Series.argmin` ``(axis: object = None, skipna: bool = True, *args, **kwargs)`` - Return int position of the minimum value. - :ref:`View ` * - :meth:`~Series.autocorr` ``(lag: typing.SupportsInt = 1)`` - Compute the lag-N autocorrelation. - :ref:`View ` * - :meth:`~Series.between` ``(left: typing.SupportsFloat, right: typing.SupportsFloat, inclusive: str = 'both')`` - Return boolean Series equivalent to left <= series <= right. - :ref:`View ` * - :meth:`~Series.case_when` ``(caselist: object)`` - Replace values where the conditions are True. - :ref:`View ` * - :meth:`~Series.clip` ``(lower: object = None, upper: object = None, *, axis: object = None, inplace: bool = False, **kwargs)`` - Trim values at input threshold(s). - :ref:`View ` * - :meth:`~Series.corr` ``(other: pandasCore.Series, method: str = 'pearson', min_periods: object = None)`` - Compute correlation with other Series. - * - :meth:`~Series.cov` ``(other: pandasCore.Series, min_periods: object = None, ddof: typing.SupportsInt = 1)`` - Compute covariance with other Series. - * - :meth:`~Series.divide` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Division of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.divmod` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return integer division and modulo of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.factorize` ``(sort: bool = False, use_na_sentinel: bool = True)`` - Encode the object as an enumerated type. - :ref:`View ` * - :meth:`~Series.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:`~Series.hist` ``(by: object = None, ax: object = None, grid: bool = True, xlabelsize: object = None, xrot: object = None, ylabelsize: object = None, yrot: object = None, figsize: object = None, bins: typing.SupportsInt = 10, backend: object = None, legend: bool = False, **kwargs)`` - Draw histogram of the input series using matplotlib. - :ref:`View ` * - :meth:`~Series.info` ``(verbose: object = None, buf: object = None, max_cols: object = None, memory_usage: object = None, show_counts: bool = True)`` - Print a concise summary of a Series. - :ref:`View ` * - :meth:`~Series.item` ``()`` - Return the first element of the underlying data as a Python scalar. - :ref:`View ` * - :meth:`~Series.memory_usage` ``(index: bool = True, deep: bool = False)`` - Return the memory usage of the Series. - :ref:`View ` * - :meth:`~Series.multiply` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Multiplication of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.product` ``(axis: object = None, skipna: bool = True, numeric_only: bool = False, min_count: typing.SupportsInt = 0, **kwargs)`` - Return the product of the values over the requested axis. Alias for... - :ref:`View ` * - :meth:`~Series.ravel` ``(order: str = 'C')`` - Return the flattened underlying data as an ndarray or ExtensionArray. - :ref:`View ` * - :meth:`~Series.rdivmod` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return reverse integer division and modulo of series and other, ele... - :ref:`View ` * - :meth:`~Series.reindex_like` ``(other: pandasCore.Series, method: object = None, copy: object = None, limit: object = None, tolerance: object = None)`` - Return a Series with matching index as other object. - * - :meth:`~Series.repeat` ``(repeats: typing.SupportsInt, axis: object = None)`` - Repeat elements of a Series. - :ref:`View ` * - :meth:`~Series.set_flags` ``(*, copy: bool = False, allows_duplicate_labels: object = None)`` - Return a new object with updated flags. - :ref:`View ` * - :meth:`~Series.subtract` ``(other: object, level: object = None, fill_value: object = None, axis: typing.SupportsInt = 0)`` - Return Subtraction of series and other, element-wise. - :ref:`View ` * - :meth:`~Series.truncate` ``(before: object = None, after: object = None, axis: object = None, copy: object = None)`` - Truncate a Series before and after some index value. - :ref:`View ` * - :meth:`~Series.values` ``()`` - Return Series as ndarray or ndarray-like - :ref:`View ` Code Examples ------------- The following examples are extracted from the test suite. .. _example-series-t-0: .. dropdown:: T (test_series_phase5.py:214) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 204 :emphasize-lines: 11 try: s = pandasCore.Series([1.0, 2.0, 3.0]) # transpose is no-op for Series transposed = s.transpose() assert transposed.to_list() == s.to_list(), "transpose should return same values" f_print_info(f" transpose(): {transposed.to_list()}") # T property transposed = s.T assert transposed.to_list() == s.to_list(), "T property should return same values" f_print_info(f" .T property: {transposed.to_list()}") f_print_success("Series transpose: passed") return True except Exception as e: f_print_error(f"Series transpose failed: {e}") return False .. _example-series-at-1: .. dropdown:: at (test_series_phase5.py:679) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 669 :emphasize-lines: 11 assert loc_result["0"] == 1.0, "loc['0'] should be 1.0" f_print_info(f" loc: {loc_result}") # iloc returns list iloc_result = s.iloc assert isinstance(iloc_result, list), "iloc should return list" assert iloc_result[0] == 1.0, "iloc[0] should be 1.0" f_print_info(f" iloc: {iloc_result}") # at returns dict at_result = s.at assert isinstance(at_result, dict), "at should return dict" f_print_info(f" at: {at_result}") # iat returns list iat_result = s.iat assert isinstance(iat_result, list), "iat should return list" f_print_info(f" iat: {iat_result}") f_print_success("Series loc/iloc/at/iat: passed") return True .. _example-series-cat-2: .. dropdown:: cat (test_accessor_descriptor.py:208) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 198 :emphasize-lines: 11 """Test that StringSeries.cat accessor works on instance""" f_print_header("Test: StringSeries instance cat accessor") try: # Create StringSeries data = ["apple", "banana", "apple", "cherry"] s = pandasCore.StringSeries(data, name="fruits") f_print_success(f"Created StringSeries: {s.values()}") # Access .cat on instance should return CategoricalAccessor cat_accessor = s.cat type_name = type(cat_accessor).__name__ f_print_info(f"type(s.cat).__name__ = {type_name}") if type_name == "CategoricalAccessor": f_print_success("s.cat returns CategoricalAccessor") else: f_print_error(f"Expected CategoricalAccessor, got {type_name}") return False # Test categories property .. _example-series-dt-3: .. dropdown:: dt (test_accessor_descriptor.py:240) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 230 :emphasize-lines: 11 """Test that DatetimeSeries.dt accessor works on instance""" f_print_header("Test: DatetimeSeries instance dt accessor") try: # Create DatetimeSeries data = ["2024-01-15", "2024-06-20", "2024-12-25"] s = pandasCore.DatetimeSeries(data) f_print_success(f"Created DatetimeSeries with {len(s)} elements") # Access .dt on instance should return DatetimeProperties dt_accessor = s.dt type_name = type(dt_accessor).__name__ f_print_info(f"type(s.dt).__name__ = {type_name}") if type_name == "DatetimeProperties": f_print_success("s.dt returns DatetimeProperties") else: f_print_error(f"Expected DatetimeProperties, got {type_name}") return False # Test year property .. _example-series-dtype-4: .. dropdown:: dtype (test_example.py:114) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 104 :emphasize-lines: 11 return False # Check name if s.name == "test_series": f_print_success(f"Name is correct: {s.name}") else: f_print_error(f"Name is wrong: {s.name}, expected 'test_series'") return False # Check dtype if s.dtype == "float64": f_print_success(f"Dtype is correct: {s.dtype}") else: f_print_error(f"Dtype is wrong: {s.dtype}, expected 'float64'") return False # Check values values = s.values() if values == data: f_print_success(f"Values are correct: {values}") else: .. _example-series-iat-5: .. dropdown:: iat (test_series_phase5.py:684) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 674 :emphasize-lines: 11 assert isinstance(iloc_result, list), "iloc should return list" assert iloc_result[0] == 1.0, "iloc[0] should be 1.0" f_print_info(f" iloc: {iloc_result}") # at returns dict at_result = s.at assert isinstance(at_result, dict), "at should return dict" f_print_info(f" at: {at_result}") # iat returns list iat_result = s.iat assert isinstance(iat_result, list), "iat should return list" f_print_info(f" iat: {iat_result}") f_print_success("Series loc/iloc/at/iat: passed") return True except Exception as e: f_print_error(f"Series loc/iloc/at/iat failed: {e}") return False .. _example-series-iloc-6: .. dropdown:: iloc (test_series_phase5.py:673) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 663 :emphasize-lines: 11 try: s = pandasCore.Series([1.0, 2.0, 3.0]) # loc returns dict loc_result = s.loc assert isinstance(loc_result, dict), "loc should return dict" assert loc_result["0"] == 1.0, "loc['0'] should be 1.0" f_print_info(f" loc: {loc_result}") # iloc returns list iloc_result = s.iloc assert isinstance(iloc_result, list), "iloc should return list" assert iloc_result[0] == 1.0, "iloc[0] should be 1.0" f_print_info(f" iloc: {iloc_result}") # at returns dict at_result = s.at assert isinstance(at_result, dict), "at should return dict" f_print_info(f" at: {at_result}") # iat returns list .. _example-series-index-7: .. dropdown:: index (test_series.py:547) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 537 :emphasize-lines: 11 # shape assert s.shape == (3,), f"Expected shape (3,), got {s.shape}" # ndim assert s.ndim == 1, f"Expected ndim=1, got {s.ndim}" # nbytes assert s.nbytes > 0, f"Expected positive nbytes, got {s.nbytes}" # index idx = s.index assert len(idx) == 3, f"Expected 3 index entries, got {len(idx)}" f_print_success("Series properties: passed") return True except Exception as e: f_print_error(f"Series properties failed: {e}") return False def f_main(): .. _example-series-loc-8: .. dropdown:: loc (test_series_phase5.py:667) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 657 :emphasize-lines: 11 def test_loc_iloc_at_iat(): """Test Series loc, iloc, at, iat properties""" f_print_header("Test: Series loc/iloc/at/iat") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # loc returns dict loc_result = s.loc assert isinstance(loc_result, dict), "loc should return dict" assert loc_result["0"] == 1.0, "loc['0'] should be 1.0" f_print_info(f" loc: {loc_result}") # iloc returns list iloc_result = s.iloc assert isinstance(iloc_result, list), "iloc should return list" assert iloc_result[0] == 1.0, "iloc[0] should be 1.0" f_print_info(f" iloc: {iloc_result}") .. _example-series-name-9: .. dropdown:: name (test_example.py:107) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 97 :emphasize-lines: 11 f_print_success("Created Series from list") # Check size if s.size == 5: f_print_success(f"Size is correct: {s.size}") else: f_print_error(f"Size is wrong: {s.size}, expected 5") return False # Check name if s.name == "test_series": f_print_success(f"Name is correct: {s.name}") else: f_print_error(f"Name is wrong: {s.name}, expected 'test_series'") return False # Check dtype if s.dtype == "float64": f_print_success(f"Dtype is correct: {s.dtype}") else: f_print_error(f"Dtype is wrong: {s.dtype}, expected 'float64'") .. _example-series-nbytes-10: .. dropdown:: nbytes (test_series.py:544) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 534 :emphasize-lines: 11 try: s = pandasCore.Series([1.0, 2.0, 3.0], name="test") # shape assert s.shape == (3,), f"Expected shape (3,), got {s.shape}" # ndim assert s.ndim == 1, f"Expected ndim=1, got {s.ndim}" # nbytes assert s.nbytes > 0, f"Expected positive nbytes, got {s.nbytes}" # index idx = s.index assert len(idx) == 3, f"Expected 3 index entries, got {len(idx)}" f_print_success("Series properties: passed") return True except Exception as e: f_print_error(f"Series properties failed: {e}") return False .. _example-series-ndim-11: .. dropdown:: ndim (test_series.py:541) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 531 :emphasize-lines: 11 """Test Series properties (shape, ndim, nbytes, index)""" f_print_header("Test: Series properties") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="test") # shape assert s.shape == (3,), f"Expected shape (3,), got {s.shape}" # ndim assert s.ndim == 1, f"Expected ndim=1, got {s.ndim}" # nbytes assert s.nbytes > 0, f"Expected positive nbytes, got {s.nbytes}" # index idx = s.index assert len(idx) == 3, f"Expected 3 index entries, got {len(idx)}" f_print_success("Series properties: passed") return True .. _example-series-plot-12: .. dropdown:: plot (test_series_phase5.py:623) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 613 :emphasize-lines: 11 # (unlike pandas which requires SparseDtype) try: sparse_acc = s.sparse f_print_info(" sparse accessor: available (pandasCore extension)") except RuntimeError as e: f_print_error("sparse accessor should work on float64 Series in pandasCore") return False # plot accessor should raise try: _ = s.plot f_print_error("plot accessor should raise error") return False except RuntimeError as e: f_print_info(" plot accessor: raises expected error") f_print_success("Series accessor errors: passed") return True except Exception as e: f_print_error(f"Series accessor errors failed: {e}") return False .. _example-series-shape-13: .. dropdown:: shape (test_series.py:538) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 528 :emphasize-lines: 11 def test_series_properties(): """Test Series properties (shape, ndim, nbytes, index)""" f_print_header("Test: Series properties") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="test") # shape assert s.shape == (3,), f"Expected shape (3,), got {s.shape}" # ndim assert s.ndim == 1, f"Expected ndim=1, got {s.ndim}" # nbytes assert s.nbytes > 0, f"Expected positive nbytes, got {s.nbytes}" # index idx = s.index assert len(idx) == 3, f"Expected 3 index entries, got {len(idx)}" .. _example-series-size-14: .. dropdown:: size (test_example.py:100) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 90 :emphasize-lines: 11 """Test Series creation from list""" f_print_header("Test: Series Creation") try: # Create Series from list data = [1.0, 2.0, 3.0, 4.0, 5.0] s = pandasCore.Series(data, name="test_series") f_print_success("Created Series from list") # Check size if s.size == 5: f_print_success(f"Size is correct: {s.size}") else: f_print_error(f"Size is wrong: {s.size}, expected 5") return False # Check name if s.name == "test_series": f_print_success(f"Name is correct: {s.name}") else: f_print_error(f"Name is wrong: {s.name}, expected 'test_series'") .. _example-series-sparse-15: .. dropdown:: sparse (test_series_phase5.py:615) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 605 :emphasize-lines: 11 try: _ = s.cat f_print_error("cat accessor should raise error for float64 Series") return False except RuntimeError as e: f_print_info(" cat accessor: raises expected error") # sparse accessor - in our implementation, works on any float64 Series # (unlike pandas which requires SparseDtype) try: sparse_acc = s.sparse f_print_info(" sparse accessor: available (pandasCore extension)") except RuntimeError as e: f_print_error("sparse accessor should work on float64 Series in pandasCore") return False # plot accessor should raise try: _ = s.plot f_print_error("plot accessor should raise error") return False .. _example-series-str-16: .. dropdown:: str (test_accessor_descriptor.py:114) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 104 :emphasize-lines: 11 """Test that StringSeries.str accessor works on instance""" f_print_header("Test: StringSeries instance str accessor") try: # Create StringSeries data = ["HELLO", "world", "Test"] s = pandasCore.StringSeries(data, name="test_strings") f_print_success(f"Created StringSeries: {s.values()}") # Access .str on instance should return StringAccessor str_accessor = s.str type_name = type(str_accessor).__name__ f_print_info(f"type(s.str).__name__ = {type_name}") if type_name == "StringAccessor": f_print_success("s.str returns StringAccessor") else: f_print_error(f"Expected StringAccessor, got {type_name}") return False # Test a string method .. _example-series-dunder-initdunder--17: .. dropdown:: __init__ (test_concat_comp.py:318) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 308 :emphasize-lines: 11 # ==================== concat Series Tests ==================== def test_concat_series_axis0(): """Test concat Series axis=0 (vertical stack)""" f_print_header("concat Series axis=0") pd_s1 = pd.Series([1.0, 2.0, 3.0]) pd_s2 = pd.Series([4.0, 5.0]) pd_result = pd.concat([pd_s1, pd_s2]) pc_s1 = pandasCore.Series([1.0, 2.0, 3.0]) pc_s2 = pandasCore.Series([4.0, 5.0]) pc_result = pandasCore.concat([pc_s1, pc_s2]) ctx.assert_equal(len(pd_result), len(pc_result), "Series axis=0 length") ctx.assert_equal(5, len(pc_result), "Series axis=0 has 5 rows") def test_concat_series_axis1(): """Test concat named Series axis=1 (horizontal join)""" f_print_header("concat Series axis=1") .. _example-series-first-18: .. dropdown:: first (test_series_phase5.py:504) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 494 :emphasize-lines: 11 def test_first_last(): """Test Series first and last methods""" f_print_header("Test: Series first/last") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # first returns head(1) result = s.first("1D") assert len(result) == 1, f"first should return 1 item" f_print_info(f" first('1D'): {result.to_list()}") # last returns tail(1) result = s.last("1D") assert len(result) == 1, f"last should return 1 item" f_print_info(f" last('1D'): {result.to_list()}") f_print_success("Series first/last: passed") return True .. _example-series-get-19: .. dropdown:: get (test_series.py:166) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 156 :emphasize-lines: 11 def test_series_get(): """Test Series get method""" f_print_header("Test: Series get") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # Test get existing key val = s.get("0") assert val == 1.0, f"Expected 1.0, got {val}" # Test get with default for non-existent key val = s.get("999", default=99.0) assert val == 99.0, f"Expected default 99.0, got {val}" f_print_success("Series get: passed") return True except Exception as e: f_print_error(f"Series get failed: {e}") .. _example-series-head-20: .. dropdown:: head (test_series.py:55) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 45 :emphasize-lines: 11 def test_series_head(): """Test Series head method""" f_print_header("Test: Series head") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) # Test default n=5 head = s.head() assert len(head) == 5, f"Expected 5 elements, got {len(head)}" assert head.to_list() == [1.0, 2.0, 3.0, 4.0, 5.0], "head(5) values incorrect" # Test custom n=3 head = s.head(3) assert len(head) == 3, f"Expected 3 elements, got {len(head)}" assert head.to_list() == [1.0, 2.0, 3.0], "head(3) values incorrect" f_print_success("Series head: passed") return True .. _example-series-idxmax-21: .. dropdown:: idxmax (test_series_phase3.py:243) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 233 :emphasize-lines: 11 return True except Exception as e: f_print_error(f"describe: {e}") return False def test_idxmax(): """Test Series.idxmax()""" f_print_header("Test: idxmax") s = pandasCore.Series([3.0, 1.0, 5.0, 2.0, 4.0]) result = s.idxmax() # Index of 5.0 is "2" (position 2) f_print_success(f"idxmax: {result}") return True def test_idxmin(): """Test Series.idxmin()""" f_print_header("Test: idxmin") s = pandasCore.Series([3.0, 1.0, 5.0, 2.0, 4.0]) result = s.idxmin() .. _example-series-idxmin-22: .. dropdown:: idxmin (test_series_phase3.py:253) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 243 :emphasize-lines: 11 result = s.idxmax() # Index of 5.0 is "2" (position 2) f_print_success(f"idxmax: {result}") return True def test_idxmin(): """Test Series.idxmin()""" f_print_header("Test: idxmin") s = pandasCore.Series([3.0, 1.0, 5.0, 2.0, 4.0]) result = s.idxmin() # Index of 1.0 is "1" (position 1) f_print_success(f"idxmin: {result}") return True def test_argmax(): """Test Series.argmax()""" f_print_header("Test: argmax") s = pandasCore.Series([3.0, 1.0, 5.0, 2.0, 4.0]) result = s.argmax() .. _example-series-last-23: .. dropdown:: last (test_series_phase5.py:509) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 499 :emphasize-lines: 11 try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # first returns head(1) result = s.first("1D") assert len(result) == 1, f"first should return 1 item" f_print_info(f" first('1D'): {result.to_list()}") # last returns tail(1) result = s.last("1D") assert len(result) == 1, f"last should return 1 item" f_print_info(f" last('1D'): {result.to_list()}") f_print_success("Series first/last: passed") return True except Exception as e: f_print_error(f"Series first/last failed: {e}") return False .. _example-series-mask-24: .. dropdown:: mask (test_series_phase2.py:605) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 595 :emphasize-lines: 11 def test_mask(): """Test Series mask method""" f_print_header("Test: Series mask") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Replace values where condition is True cond = [True, False, True, False, True] s_mask = s.mask(cond, other=0.0) expected = [0.0, 2.0, 0.0, 4.0, 0.0] assert s_mask.to_list() == expected, f"Expected {expected}, got {s_mask.to_list()}" f_print_success("mask: passed") return True except Exception as e: f_print_error(f"mask failed: {e}") return False .. _example-series-nlargest-25: .. dropdown:: nlargest (test_series_phase3.py:421) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 411 :emphasize-lines: 11 values = result.values() # With method='average': 1.0 gets rank 1.5, 3.0 gets rank 3, 4.0 gets rank 4, 5.0 gets rank 5 f_print_success(f"rank: {values}") return True def test_nlargest(): """Test Series.nlargest()""" f_print_header("Test: nlargest") s = pandasCore.Series([3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0]) result = s.nlargest(3) values = result.values() if set(values) == {9.0, 6.0, 5.0}: f_print_success(f"nlargest(3): {values} contains 9.0, 6.0, 5.0") return True f_print_error(f"nlargest(3): {values} incorrect") return False def test_nsmallest(): """Test Series.nsmallest()""" .. _example-series-nsmallest-26: .. dropdown:: nsmallest (test_series_phase3.py:434) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 424 :emphasize-lines: 11 f_print_success(f"nlargest(3): {values} contains 9.0, 6.0, 5.0") return True f_print_error(f"nlargest(3): {values} incorrect") return False def test_nsmallest(): """Test Series.nsmallest()""" f_print_header("Test: nsmallest") s = pandasCore.Series([3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0]) result = s.nsmallest(3) values = result.values() if set(values) == {1.0, 1.0, 2.0}: f_print_success(f"nsmallest(3): {values} contains 1.0, 1.0, 2.0") return True f_print_error(f"nsmallest(3): {values} incorrect") return False def test_value_counts(): """Test Series.value_counts()""" .. _example-series-sample-27: .. dropdown:: sample (test_series_phase5.py:457) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 447 :emphasize-lines: 11 # ============================================================================ def test_sample(): """Test Series sample method""" f_print_header("Test: Series sample") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Sample n items sampled = s.sample(n=2, random_state=42) assert len(sampled) == 2, f"sample(n=2) should return 2 items, got {len(sampled)}" f_print_info(f" sample(n=2): {sampled.to_list()}") # Sample fraction sampled = s.sample(frac=0.4, random_state=42) assert len(sampled) == 2, f"sample(frac=0.4) should return 2 items, got {len(sampled)}" f_print_info(f" sample(frac=0.4): {sampled.to_list()}") f_print_success("Series sample: passed") return True .. _example-series-tail-28: .. dropdown:: tail (test_series.py:79) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 69 :emphasize-lines: 11 def test_series_tail(): """Test Series tail method""" f_print_header("Test: Series tail") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]) # Test default n=5 tail = s.tail() assert len(tail) == 5, f"Expected 5 elements, got {len(tail)}" assert tail.to_list() == [6.0, 7.0, 8.0, 9.0, 10.0], "tail(5) values incorrect" # Test custom n=3 tail = s.tail(3) assert len(tail) == 3, f"Expected 3 elements, got {len(tail)}" assert tail.to_list() == [8.0, 9.0, 10.0], "tail(3) values incorrect" f_print_success("Series tail: passed") return True .. _example-series-take-29: .. dropdown:: take (test_series.py:227) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 217 :emphasize-lines: 11 def test_series_take(): """Test Series take method""" f_print_header("Test: Series take") try: s = pandasCore.Series([10.0, 20.0, 30.0, 40.0, 50.0]) # Take specific indices taken = s.take([0, 2, 4]) assert len(taken) == 3, f"Expected 3 elements, got {len(taken)}" assert taken.to_list() == [10.0, 30.0, 50.0], f"take values incorrect: {taken.to_list()}" f_print_success("Series take: passed") return True except Exception as e: f_print_error(f"Series take failed: {e}") return False .. _example-series-where-30: .. dropdown:: where (test_series_phase2.py:585) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 575 :emphasize-lines: 11 def test_where(): """Test Series where method""" f_print_header("Test: Series where") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Keep values where condition is True cond = [True, False, True, False, True] s_where = s.where(cond, other=0.0) expected = [1.0, 0.0, 3.0, 0.0, 5.0] assert s_where.to_list() == expected, f"Expected {expected}, got {s_where.to_list()}" f_print_success("where: passed") return True except Exception as e: f_print_error(f"where failed: {e}") return False .. _example-series-xs-31: .. dropdown:: xs (test_series_phase5.py:481) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 471 :emphasize-lines: 11 def test_xs(): """Test Series xs method""" f_print_header("Test: Series xs") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # xs returns value at label value = s.xs("0") assert value == 1.0, f"xs('0') should return 1.0, got {value}" f_print_info(f" xs('0'): {value}") value = s.xs("2") assert value == 3.0, f"xs('2') should return 3.0, got {value}" f_print_info(f" xs('2'): {value}") f_print_success("Series xs: passed") return True except Exception as e: .. _example-series-drop-32: .. dropdown:: drop (test_series_phase2.py:201) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 191 :emphasize-lines: 11 def test_drop(): """Test Series drop method""" f_print_header("Test: Series drop") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Drop single label s_dropped = s.drop("1") assert len(s_dropped) == 4, f"Expected length 4, got {len(s_dropped)}" # Drop multiple labels s_dropped = s.drop(["0", "2"]) assert len(s_dropped) == 3, f"Expected length 3, got {len(s_dropped)}" f_print_success("drop: passed") return True except Exception as e: f_print_error(f"drop failed: {e}") .. _example-series-droplevel-33: .. dropdown:: droplevel (test_series_phase2.py:263) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 253 :emphasize-lines: 11 def test_droplevel(): """Test Series droplevel method""" f_print_header("Test: Series droplevel") try: # droplevel requires MultiIndex, but should raise for regular index s = pandasCore.Series([1.0, 2.0, 3.0]) try: s.droplevel(0) # If no MultiIndex, it should raise except RuntimeError as e: if "MultiIndex" in str(e): print(f" Note: droplevel RuntimeError (expected for non-MultiIndex): {e}") else: raise f_print_success("droplevel: passed (raises for non-MultiIndex)") return True except Exception as e: .. _example-series-pop-34: .. dropdown:: pop (test_series.py:332) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 322 :emphasize-lines: 11 def test_series_pop(): """Test Series pop method""" f_print_header("Test: Series pop") try: s = pandasCore.Series([10.0, 20.0, 30.0]) # Pop by label val = s.pop("1") # Pop the element at index "1" (value 20.0) assert val == 20.0, f"Expected 20.0, got {val}" assert len(s) == 2, f"After pop, expected 2 elements, got {len(s)}" f_print_success("Series pop: passed") return True except Exception as e: f_print_error(f"Series pop failed: {e}") return False .. _example-series-reindex-35: .. dropdown:: reindex (test_series_phase2.py:78) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 68 :emphasize-lines: 11 def test_reindex(): """Test Series reindex method""" f_print_header("Test: Series reindex") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # Reindex with new labels s_reindexed = s.reindex(["0", "1", "5"]) assert len(s_reindexed) == 3, f"Expected length 3, got {len(s_reindexed)}" # Value at "5" should be NaN (not found in original) vals = s_reindexed.to_list() assert vals[0] == 1.0, f"Value at '0' should be 1.0, got {vals[0]}" assert math.isnan(vals[2]), f"Value at '5' should be NaN, got {vals[2]}" f_print_success("reindex: passed") return True except Exception as e: .. _example-series-rename-36: .. dropdown:: rename (test_series_phase2.py:40) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 30 :emphasize-lines: 11 # ============================================================================= def test_rename(): """Test Series rename method""" f_print_header("Test: Series rename") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="original") # Rename by passing new name s_renamed = s.rename("new_name") assert s_renamed.name == "new_name", f"Expected name 'new_name', got {s_renamed.name}" assert s.name == "original", "Original Series name should not change" f_print_success("rename: passed") return True except Exception as e: f_print_error(f"rename failed: {e}") return False .. _example-series-rename_axis-37: .. dropdown:: rename_axis (test_series_phase2.py:59) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 49 :emphasize-lines: 11 def test_rename_axis(): """Test Series rename_axis method""" f_print_header("Test: Series rename_axis") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # Rename axis s_renamed = s.rename_axis("my_index") # Should not raise, returns Series assert len(s_renamed) == 3, "Length should be preserved" f_print_success("rename_axis: passed") return True except Exception as e: f_print_error(f"rename_axis failed: {e}") return False .. _example-series-reorder_levels-38: .. dropdown:: reorder_levels (test_series_phase2.py:287) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 277 :emphasize-lines: 11 def test_reorder_levels(): """Test Series reorder_levels method""" f_print_header("Test: Series reorder_levels") try: # reorder_levels requires MultiIndex s = pandasCore.Series([1.0, 2.0, 3.0]) try: s.reorder_levels([1, 0]) except RuntimeError as e: if "MultiIndex" in str(e): print(f" Note: reorder_levels RuntimeError (expected for non-MultiIndex): {e}") else: raise f_print_success("reorder_levels: passed (raises for non-MultiIndex)") return True except Exception as e: f_print_error(f"reorder_levels failed: {e}") .. _example-series-replace-39: .. dropdown:: replace (test_series_phase2.py:537) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 527 :emphasize-lines: 11 # ============================================================================= def test_replace(): """Test Series replace method""" f_print_header("Test: Series replace") try: s = pandasCore.Series([1.0, 2.0, 3.0, 2.0, 1.0]) # Replace single value s_replaced = s.replace(2.0, 99.0) expected = [1.0, 99.0, 3.0, 99.0, 1.0] assert s_replaced.to_list() == expected, f"Expected {expected}, got {s_replaced.to_list()}" # Replace with dict s_replaced = s.replace({1.0: 10.0, 3.0: 30.0}) expected = [10.0, 2.0, 30.0, 2.0, 10.0] assert s_replaced.to_list() == expected, f"Expected {expected}, got {s_replaced.to_list()}" f_print_success("replace: passed") return True .. _example-series-reset_index-40: .. dropdown:: reset_index (test_series_phase2.py:160) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 150 :emphasize-lines: 11 def test_reset_index(): """Test Series reset_index method""" f_print_header("Test: Series reset_index") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") # Reset index with drop=True returns Series s_reset = s.reset_index(drop=True) assert len(s_reset) == 3, f"Expected length 3, got {len(s_reset)}" # Reset index with drop=False returns DataFrame df = s.reset_index(drop=False) assert df is not None, "reset_index(drop=False) should return DataFrame" f_print_success("reset_index: passed") return True except Exception as e: f_print_error(f"reset_index failed: {e}") .. _example-series-set_axis-41: .. dropdown:: set_axis (test_series_phase2.py:182) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 172 :emphasize-lines: 11 def test_set_axis(): """Test Series set_axis method""" f_print_header("Test: Series set_axis") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # Set new axis labels s_new = s.set_axis(["a", "b", "c"]) keys = s_new.keys() assert keys == ["a", "b", "c"], f"Expected ['a', 'b', 'c'], got {keys}" f_print_success("set_axis: passed") return True except Exception as e: f_print_error(f"set_axis failed: {e}") return False .. _example-series-swaplevel-42: .. dropdown:: swaplevel (test_series_phase2.py:310) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 300 :emphasize-lines: 11 def test_swaplevel(): """Test Series swaplevel method""" f_print_header("Test: Series swaplevel") try: # swaplevel requires MultiIndex s = pandasCore.Series([1.0, 2.0, 3.0]) try: s.swaplevel() except RuntimeError as e: if "MultiIndex" in str(e): print(f" Note: swaplevel RuntimeError (expected for non-MultiIndex): {e}") else: raise f_print_success("swaplevel: passed (raises for non-MultiIndex)") return True except Exception as e: f_print_error(f"swaplevel failed: {e}") .. _example-series-backfill-43: .. dropdown:: backfill (test_series_phase2.py:477) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 467 :emphasize-lines: 11 return False def test_backfill(): """Test Series backfill method (alias for bfill)""" f_print_header("Test: Series backfill") try: s = pandasCore.Series([float('nan'), 2.0, float('nan')]) s_filled = s.backfill() expected = [2.0, 2.0, float('nan')] # Last NaN can't be backfilled result = s_filled.to_list() assert result[0] == 2.0 and result[1] == 2.0, f"Backfill incorrect: {result}" f_print_success("backfill: passed") return True except Exception as e: f_print_error(f"backfill failed: {e}") return False .. _example-series-bfill-44: .. dropdown:: bfill (test_series_phase2.py:459) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 449 :emphasize-lines: 11 return False def test_bfill(): """Test Series bfill method""" f_print_header("Test: Series bfill") try: s = pandasCore.Series([float('nan'), 2.0, float('nan'), float('nan'), 5.0]) s_filled = s.bfill() expected = [2.0, 2.0, 5.0, 5.0, 5.0] assert s_filled.to_list() == expected, f"Expected {expected}, got {s_filled.to_list()}" f_print_success("bfill: passed") return True except Exception as e: f_print_error(f"bfill failed: {e}") return False .. _example-series-dropna-45: .. dropdown:: dropna (test_series_phase2.py:405) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 395 :emphasize-lines: 11 return False def test_dropna(): """Test Series dropna method""" f_print_header("Test: Series dropna") try: s = pandasCore.Series([1.0, float('nan'), 3.0, float('nan'), 5.0]) s_clean = s.dropna() assert len(s_clean) == 3, f"Expected 3 elements after dropna, got {len(s_clean)}" assert s_clean.to_list() == [1.0, 3.0, 5.0], f"Values incorrect: {s_clean.to_list()}" f_print_success("dropna: passed") return True except Exception as e: f_print_error(f"dropna failed: {e}") return False .. _example-series-ffill-46: .. dropdown:: ffill (test_series_phase2.py:441) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 431 :emphasize-lines: 11 return False def test_ffill(): """Test Series ffill method""" f_print_header("Test: Series ffill") try: s = pandasCore.Series([1.0, float('nan'), float('nan'), 4.0, float('nan')]) s_filled = s.ffill() expected = [1.0, 1.0, 1.0, 4.0, 4.0] assert s_filled.to_list() == expected, f"Expected {expected}, got {s_filled.to_list()}" f_print_success("ffill: passed") return True except Exception as e: f_print_error(f"ffill failed: {e}") return False .. _example-series-fillna-47: .. dropdown:: fillna (test_series_phase2.py:424) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 414 :emphasize-lines: 11 def test_fillna(): """Test Series fillna method""" f_print_header("Test: Series fillna") try: s = pandasCore.Series([1.0, float('nan'), 3.0, float('nan'), 5.0]) # Fill with scalar value s_filled = s.fillna(0.0) assert s_filled.to_list() == [1.0, 0.0, 3.0, 0.0, 5.0], f"Values incorrect: {s_filled.to_list()}" f_print_success("fillna: passed") return True except Exception as e: f_print_error(f"fillna failed: {e}") return False def test_ffill(): .. _example-series-interpolate-48: .. dropdown:: interpolate (test_series_phase2.py:514) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 504 :emphasize-lines: 11 return False def test_interpolate(): """Test Series interpolate method""" f_print_header("Test: Series interpolate") try: s = pandasCore.Series([1.0, float('nan'), 3.0]) s_interp = s.interpolate(method="linear") expected = [1.0, 2.0, 3.0] assert s_interp.to_list() == expected, f"Expected {expected}, got {s_interp.to_list()}" f_print_success("interpolate: passed") return True except Exception as e: f_print_error(f"interpolate failed: {e}") return False .. _example-series-isna-49: .. dropdown:: isna (test_series_phase2.py:335) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 325 :emphasize-lines: 11 # NA Handling Tests (Methods 15-25) # ============================================================================= def test_isna(): """Test Series isna method""" f_print_header("Test: Series isna") try: s = pandasCore.Series([1.0, float('nan'), 3.0, float('nan')]) mask = s.isna() assert len(mask) == 4, f"Expected 4 elements, got {len(mask)}" assert mask == [False, True, False, True], f"Unexpected mask: {mask}" f_print_success("isna: passed") return True except Exception as e: f_print_error(f"isna failed: {e}") return False .. _example-series-isnull-50: .. dropdown:: isnull (test_series_phase2.py:371) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 361 :emphasize-lines: 11 return False def test_isnull(): """Test Series isnull method (alias for isna)""" f_print_header("Test: Series isnull") try: s = pandasCore.Series([1.0, float('nan'), 3.0]) mask = s.isnull() assert mask == [False, True, False], f"Unexpected mask: {mask}" f_print_success("isnull: passed") return True except Exception as e: f_print_error(f"isnull failed: {e}") return False def test_notnull(): .. _example-series-notna-51: .. dropdown:: notna (test_series_phase2.py:353) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 343 :emphasize-lines: 11 return False def test_notna(): """Test Series notna method""" f_print_header("Test: Series notna") try: s = pandasCore.Series([1.0, float('nan'), 3.0, float('nan')]) mask = s.notna() assert len(mask) == 4, f"Expected 4 elements, got {len(mask)}" assert mask == [True, False, True, False], f"Unexpected mask: {mask}" f_print_success("notna: passed") return True except Exception as e: f_print_error(f"notna failed: {e}") return False .. _example-series-notnull-52: .. dropdown:: notnull (test_series_phase2.py:388) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 378 :emphasize-lines: 11 return False def test_notnull(): """Test Series notnull method (alias for notna)""" f_print_header("Test: Series notnull") try: s = pandasCore.Series([1.0, float('nan'), 3.0]) mask = s.notnull() assert mask == [True, False, True], f"Unexpected mask: {mask}" f_print_success("notnull: passed") return True except Exception as e: f_print_error(f"notnull failed: {e}") return False def test_dropna(): .. _example-series-pad-53: .. dropdown:: pad (test_series_phase2.py:496) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 486 :emphasize-lines: 11 return False def test_pad(): """Test Series pad method (alias for ffill)""" f_print_header("Test: Series pad") try: s = pandasCore.Series([1.0, float('nan'), float('nan')]) s_filled = s.pad() expected = [1.0, 1.0, 1.0] assert s_filled.to_list() == expected, f"Expected {expected}, got {s_filled.to_list()}" f_print_success("pad: passed") return True except Exception as e: f_print_error(f"pad failed: {e}") return False .. _example-series-count-54: .. dropdown:: count (test_series_phase3.py:218) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 208 :emphasize-lines: 11 f_print_success(f"mode: {values} contains 2.0") return True f_print_error(f"mode: {values} does not contain 2.0") return False def test_count(): """Test Series.count()""" f_print_header("Test: count") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.count() if result == 5: f_print_success(f"count: {result} == 5") return True f_print_error(f"count: {result} != 5") return False def test_describe(): """Test Series.describe()""" f_print_header("Test: describe") .. _example-series-cummax-55: .. dropdown:: cummax (test_series_phase3.py:329) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 319 :emphasize-lines: 11 f_print_success(f"cummin: {values} == {expected}") return True f_print_error(f"cummin: {values} != {expected}") return False def test_cummax(): """Test Series.cummax()""" f_print_header("Test: cummax") s = pandasCore.Series([1.0, 3.0, 2.0, 5.0, 4.0]) result = s.cummax() values = result.values() expected = [1.0, 3.0, 3.0, 5.0, 5.0] if values == expected: f_print_success(f"cummax: {values} == {expected}") return True f_print_error(f"cummax: {values} != {expected}") return False def test_diff(): .. _example-series-cummin-56: .. dropdown:: cummin (test_series_phase3.py:315) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 305 :emphasize-lines: 11 f_print_success(f"cumprod: {values} == {expected}") return True f_print_error(f"cumprod: {values} != {expected}") return False def test_cummin(): """Test Series.cummin()""" f_print_header("Test: cummin") s = pandasCore.Series([5.0, 3.0, 4.0, 1.0, 2.0]) result = s.cummin() values = result.values() expected = [5.0, 3.0, 3.0, 1.0, 1.0] if values == expected: f_print_success(f"cummin: {values} == {expected}") return True f_print_error(f"cummin: {values} != {expected}") return False def test_cummax(): .. _example-series-cumprod-57: .. dropdown:: cumprod (test_series_phase3.py:301) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 291 :emphasize-lines: 11 f_print_success(f"cumsum: {values} == {expected}") return True f_print_error(f"cumsum: {values} != {expected}") return False def test_cumprod(): """Test Series.cumprod()""" f_print_header("Test: cumprod") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.cumprod() values = result.values() expected = [1.0, 2.0, 6.0, 24.0, 120.0] if values == expected: f_print_success(f"cumprod: {values} == {expected}") return True f_print_error(f"cumprod: {values} != {expected}") return False def test_cummin(): .. _example-series-cumsum-58: .. dropdown:: cumsum (test_series_phase3.py:287) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 277 :emphasize-lines: 11 f_print_success(f"argmin: {result} == 1") return True f_print_error(f"argmin: {result} != 1") return False def test_cumsum(): """Test Series.cumsum()""" f_print_header("Test: cumsum") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.cumsum() values = result.values() expected = [1.0, 3.0, 6.0, 10.0, 15.0] if values == expected: f_print_success(f"cumsum: {values} == {expected}") return True f_print_error(f"cumsum: {values} != {expected}") return False def test_cumprod(): .. _example-series-describe-59: .. dropdown:: describe (test_series_phase3.py:231) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 221 :emphasize-lines: 11 return True f_print_error(f"count: {result} != 5") return False def test_describe(): """Test Series.describe()""" f_print_header("Test: describe") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) try: result = s.describe() f_print_success(f"describe: returned DataFrame") return True except Exception as e: f_print_error(f"describe: {e}") return False def test_idxmax(): """Test Series.idxmax()""" f_print_header("Test: idxmax") .. _example-series-kurt-60: .. dropdown:: kurt (test_series_phase3.py:168) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 158 :emphasize-lines: 11 f_print_success(f"skew: {result} ~= 0.0 (symmetric)") return True f_print_error(f"skew: {result} != ~0.0") return False def test_kurt(): """Test Series.kurt()""" f_print_header("Test: kurt") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.kurt() # Result should be a valid float if result is not None: f_print_success(f"kurt: {result} (valid result)") return True f_print_error("kurt: returned None") return False def test_kurtosis(): """Test Series.kurtosis() - alias for kurt""" .. _example-series-kurtosis-61: .. dropdown:: kurtosis (test_series_phase3.py:181) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 171 :emphasize-lines: 11 f_print_success(f"kurt: {result} (valid result)") return True f_print_error("kurt: returned None") return False def test_kurtosis(): """Test Series.kurtosis() - alias for kurt""" f_print_header("Test: kurtosis") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.kurtosis() if result is not None: f_print_success(f"kurtosis: {result} (valid result)") return True f_print_error("kurtosis: returned None") return False def test_quantile(): """Test Series.quantile()""" f_print_header("Test: quantile") .. _example-series-max-62: .. dropdown:: max (test_series_phase3.py:105) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 95 :emphasize-lines: 11 f_print_success(f"min: {result} == 1.0") return True f_print_error(f"min: {result} != 1.0") return False def test_max(): """Test Series.max()""" f_print_header("Test: max") s = pandasCore.Series([3.0, 1.0, 4.0, 1.0, 5.0]) result = s.max() if result == 5.0: f_print_success(f"max: {result} == 5.0") return True f_print_error(f"max: {result} != 5.0") return False def test_std(): """Test Series.std()""" f_print_header("Test: std") .. _example-series-mean-63: .. dropdown:: mean (test_series_phase3.py:69) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 59 :emphasize-lines: 11 f_print_success(f"product: {result} == 120.0") return True f_print_error(f"product: {result} != 120.0") return False def test_mean(): """Test Series.mean()""" f_print_header("Test: mean") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.mean() if result == 3.0: f_print_success(f"mean: {result} == 3.0") return True f_print_error(f"mean: {result} != 3.0") return False def test_median(): """Test Series.median()""" f_print_header("Test: median") .. _example-series-median-64: .. dropdown:: median (test_series_phase3.py:81) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 71 :emphasize-lines: 11 f_print_success(f"mean: {result} == 3.0") return True f_print_error(f"mean: {result} != 3.0") return False def test_median(): """Test Series.median()""" f_print_header("Test: median") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.median() if result == 3.0: f_print_success(f"median: {result} == 3.0") return True f_print_error(f"median: {result} != 3.0") return False def test_min(): """Test Series.min()""" f_print_header("Test: min") .. _example-series-min-65: .. dropdown:: min (test_series_phase3.py:93) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 83 :emphasize-lines: 11 f_print_success(f"median: {result} == 3.0") return True f_print_error(f"median: {result} != 3.0") return False def test_min(): """Test Series.min()""" f_print_header("Test: min") s = pandasCore.Series([3.0, 1.0, 4.0, 1.0, 5.0]) result = s.min() if result == 1.0: f_print_success(f"min: {result} == 1.0") return True f_print_error(f"min: {result} != 1.0") return False def test_max(): """Test Series.max()""" f_print_header("Test: max") .. _example-series-mode-66: .. dropdown:: mode (test_series_phase3.py:205) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 195 :emphasize-lines: 11 f_print_success(f"quantile(0.5): {result} == 3.0") return True f_print_error(f"quantile(0.5): {result} != 3.0") return False def test_mode(): """Test Series.mode()""" f_print_header("Test: mode") s = pandasCore.Series([1.0, 2.0, 2.0, 3.0, 2.0]) result = s.mode() values = result.values() if 2.0 in values: f_print_success(f"mode: {values} contains 2.0") return True f_print_error(f"mode: {values} does not contain 2.0") return False def test_count(): """Test Series.count()""" .. _example-series-nunique-67: .. dropdown:: nunique (test_series_phase2.py:718) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 708 :emphasize-lines: 11 return False def test_nunique(): """Test Series nunique method""" f_print_header("Test: Series nunique") try: s = pandasCore.Series([1.0, 2.0, 2.0, 3.0, 1.0, 3.0]) count = s.nunique() assert count == 3, f"Expected 3 unique values, got {count}" # Test with NaN s_nan = pandasCore.Series([1.0, float('nan'), 2.0, float('nan')]) count_dropna = s_nan.nunique(dropna=True) assert count_dropna == 2, f"Expected 2 unique (dropna=True), got {count_dropna}" f_print_success("nunique: passed") return True except Exception as e: .. _example-series-prod-68: .. dropdown:: prod (test_series_phase3.py:45) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 35 :emphasize-lines: 11 f_print_success(f"sum: {result} == 15.0") return True f_print_error(f"sum: {result} != 15.0") return False def test_prod(): """Test Series.prod()""" f_print_header("Test: prod") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.prod() if result == 120.0: f_print_success(f"prod: {result} == 120.0") return True f_print_error(f"prod: {result} != 120.0") return False def test_product(): """Test Series.product() - alias for prod""" f_print_header("Test: product") .. _example-series-quantile-69: .. dropdown:: quantile (test_series_phase3.py:193) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 183 :emphasize-lines: 11 f_print_success(f"kurtosis: {result} (valid result)") return True f_print_error("kurtosis: returned None") return False def test_quantile(): """Test Series.quantile()""" f_print_header("Test: quantile") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.quantile(0.5) if result == 3.0: f_print_success(f"quantile(0.5): {result} == 3.0") return True f_print_error(f"quantile(0.5): {result} != 3.0") return False def test_mode(): """Test Series.mode()""" f_print_header("Test: mode") .. _example-series-sem-70: .. dropdown:: sem (test_series_phase3.py:142) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 132 :emphasize-lines: 11 f_print_success(f"var: {result} == 2.5") return True f_print_error(f"var: {result} != 2.5") return False def test_sem(): """Test Series.sem()""" f_print_header("Test: sem") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.sem() expected = math.sqrt(2.5) / math.sqrt(5) if abs(result - expected) < 1e-10: f_print_success(f"sem: {result} ~= {expected}") return True f_print_error(f"sem: {result} != {expected}") return False def test_skew(): """Test Series.skew()""" .. _example-series-skew-71: .. dropdown:: skew (test_series_phase3.py:155) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 145 :emphasize-lines: 11 f_print_success(f"sem: {result} ~= {expected}") return True f_print_error(f"sem: {result} != {expected}") return False def test_skew(): """Test Series.skew()""" f_print_header("Test: skew") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.skew() # Symmetric distribution should have skew close to 0 if abs(result) < 1e-10: f_print_success(f"skew: {result} ~= 0.0 (symmetric)") return True f_print_error(f"skew: {result} != ~0.0") return False def test_kurt(): """Test Series.kurt()""" .. _example-series-std-72: .. dropdown:: std (test_series_phase3.py:117) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 107 :emphasize-lines: 11 f_print_success(f"max: {result} == 5.0") return True f_print_error(f"max: {result} != 5.0") return False def test_std(): """Test Series.std()""" f_print_header("Test: std") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.std() expected = math.sqrt(2.5) # Sample std with ddof=1 if abs(result - expected) < 1e-10: f_print_success(f"std: {result} ~= {expected}") return True f_print_error(f"std: {result} != {expected}") return False def test_var(): """Test Series.var()""" .. _example-series-sum-73: .. dropdown:: sum (test_series_phase3.py:33) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 23 :emphasize-lines: 11 # Direct imports import pandasCore import pandas as pd def test_sum(): """Test Series.sum()""" f_print_header("Test: sum") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.sum() if result == 15.0: f_print_success(f"sum: {result} == 15.0") return True f_print_error(f"sum: {result} != 15.0") return False def test_prod(): """Test Series.prod()""" f_print_header("Test: prod") .. _example-series-value_counts-74: .. dropdown:: value_counts (test_series_phase3.py:447) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 437 :emphasize-lines: 11 f_print_success(f"nsmallest(3): {values} contains 1.0, 1.0, 2.0") return True f_print_error(f"nsmallest(3): {values} incorrect") return False def test_value_counts(): """Test Series.value_counts()""" f_print_header("Test: value_counts") s = pandasCore.Series([1.0, 2.0, 2.0, 3.0, 3.0, 3.0]) result = s.value_counts() f_print_success(f"value_counts: returned IntSeries") return True def test_agg(): """Test Series.agg()""" f_print_header("Test: agg") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.agg("sum") if result == 15.0: .. _example-series-var-75: .. dropdown:: var (test_series_phase3.py:130) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 120 :emphasize-lines: 11 f_print_success(f"std: {result} ~= {expected}") return True f_print_error(f"std: {result} != {expected}") return False def test_var(): """Test Series.var()""" f_print_header("Test: var") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.var() if result == 2.5: # Sample variance with ddof=1 f_print_success(f"var: {result} == 2.5") return True f_print_error(f"var: {result} != 2.5") return False def test_sem(): """Test Series.sem()""" f_print_header("Test: sem") .. _example-series-agg-76: .. dropdown:: agg (test_series_phase3.py:456) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 446 :emphasize-lines: 11 s = pandasCore.Series([1.0, 2.0, 2.0, 3.0, 3.0, 3.0]) result = s.value_counts() f_print_success(f"value_counts: returned IntSeries") return True def test_agg(): """Test Series.agg()""" f_print_header("Test: agg") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.agg("sum") if result == 15.0: f_print_success(f"agg('sum'): {result} == 15.0") return True f_print_error(f"agg('sum'): {result} != 15.0") return False def test_aggregate(): """Test Series.aggregate() - alias for agg""" f_print_header("Test: aggregate") .. _example-series-aggregate-77: .. dropdown:: aggregate (test_series_phase3.py:468) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 458 :emphasize-lines: 11 f_print_success(f"agg('sum'): {result} == 15.0") return True f_print_error(f"agg('sum'): {result} != 15.0") return False def test_aggregate(): """Test Series.aggregate() - alias for agg""" f_print_header("Test: aggregate") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.aggregate("mean") if result == 3.0: f_print_success(f"aggregate('mean'): {result} == 3.0") return True f_print_error(f"aggregate('mean'): {result} != 3.0") return False def test_apply(): """Test Series.apply()""" f_print_header("Test: apply") .. _example-series-apply-78: .. dropdown:: apply (test_series_phase3.py:480) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 470 :emphasize-lines: 11 f_print_success(f"aggregate('mean'): {result} == 3.0") return True f_print_error(f"aggregate('mean'): {result} != 3.0") return False def test_apply(): """Test Series.apply()""" f_print_header("Test: apply") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.apply(lambda x: x * 2) values = result.values() expected = [2.0, 4.0, 6.0, 8.0, 10.0] if values == expected: f_print_success(f"apply(x*2): {values} == {expected}") return True f_print_error(f"apply(x*2): {values} != {expected}") return False def test_map(): .. _example-series-ewm-79: .. dropdown:: ewm (test_series_phase5.py:361) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 351 :emphasize-lines: 11 def test_ewm_placeholder(): """Test Series ewm functionality""" f_print_header("Test: Series ewm") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # ewm should return a SeriesEWM object with working mean() ewm_obj = s.ewm(span=2) result = ewm_obj.mean() f_print_info(f" ewm(span=2).mean() = {result.tolist()}") f_print_success("Series ewm: passed") return True except Exception as e: f_print_error(f"Series ewm failed: {e}") return False .. _example-series-expanding-80: .. dropdown:: expanding (test_series_phase5.py:342) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 332 :emphasize-lines: 11 def test_expanding_placeholder(): """Test Series expanding functionality""" f_print_header("Test: Series expanding") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # expanding should return a SeriesExpanding object with working mean() exp_obj = s.expanding() result = exp_obj.mean() f_print_info(f" expanding().mean() = {result.tolist()}") f_print_success("Series expanding: passed") return True except Exception as e: f_print_error(f"Series expanding failed: {e}") return False .. _example-series-groupby-81: .. dropdown:: groupby (test_series_phase5.py:296) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 286 :emphasize-lines: 11 # Grouping & Windowing Methods Tests # ============================================================================ def test_groupby_placeholder(): """Test Series groupby""" f_print_header("Test: Series groupby") try: # Test groupby with level=0 (group by index) s = pandasCore.Series([1.0, 2.0, 3.0, 4.0], index=['a', 'a', 'b', 'b']) gb = s.groupby(level=0) result = gb.sum() assert result.tolist() == [3.0, 7.0], f"Expected [3.0, 7.0], got {result.tolist()}" f_print_info(f" groupby(level=0).sum() = {result.tolist()}") # Test groupby with by= list s2 = pandasCore.Series([10.0, 20.0, 30.0]) gb2 = s2.groupby(by=['x', 'x', 'y']) result2 = gb2.sum() assert result2.tolist() == [30.0, 30.0], f"Expected [30.0, 30.0], got {result2.tolist()}" f_print_info(f" groupby(by=list).sum() = {result2.tolist()}") .. _example-series-map-82: .. dropdown:: map (test_series_phase3.py:495) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 485 :emphasize-lines: 11 return True f_print_error(f"apply(x*2): {values} != {expected}") return False def test_map(): """Test Series.map()""" f_print_header("Test: map") s = pandasCore.Series([1.0, 2.0, 3.0]) mapping = {1.0: 10.0, 2.0: 20.0, 3.0: 30.0} result = s.map(mapping) values = result.values() expected = [10.0, 20.0, 30.0] if values == expected: f_print_success(f"map(dict): {values} == {expected}") return True f_print_error(f"map(dict): {values} != {expected}") return False def test_transform(): .. _example-series-pipe-83: .. dropdown:: pipe (test_series_phase3.py:527) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 517 :emphasize-lines: 11 def test_pipe(): """Test Series.pipe()""" f_print_header("Test: pipe") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) def double_sum(series): return series.sum() * 2 result = s.pipe(double_sum) if result == 30.0: f_print_success(f"pipe(double_sum): {result} == 30.0") return True f_print_error(f"pipe(double_sum): {result} != 30.0") return False def test_all(): """Test Series.all()""" f_print_header("Test: all") .. _example-series-resample-84: .. dropdown:: resample (test_series_phase5.py:381) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 371 :emphasize-lines: 11 def test_resample_placeholder(): """Test Series resample works""" f_print_header("Test: Series resample (placeholder)") try: dates = pandasCore.date_range('2023-01-01', periods=3, freq='D') s = pandasCore.Series([1.0, 2.0, 3.0], index=dates) # resample should return a SeriesResampler object resampler = s.resample("D") result = resampler.sum() f_print_info(f" resample('D').sum() returned {len(result)} values") f_print_success("Series resample placeholder: passed") return True except Exception as e: f_print_error(f"Series resample placeholder failed: {e}") return False .. _example-series-rolling-85: .. dropdown:: rolling (test_series_phase5.py:323) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 313 :emphasize-lines: 11 def test_rolling_placeholder(): """Test Series rolling works""" f_print_header("Test: Series rolling (placeholder)") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # rolling should return a Rolling object r = s.rolling(window=2) result = r.mean() f_print_info(f" rolling(2).mean() returned {len(result)} values") f_print_success("Series rolling placeholder: passed") return True except Exception as e: f_print_error(f"Series rolling placeholder failed: {e}") return False .. _example-series-transform-86: .. dropdown:: transform (test_series_phase3.py:509) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 499 :emphasize-lines: 11 f_print_success(f"map(dict): {values} == {expected}") return True f_print_error(f"map(dict): {values} != {expected}") return False def test_transform(): """Test Series.transform()""" f_print_header("Test: transform") s = pandasCore.Series([1.0, 4.0, 9.0, 16.0]) result = s.transform("sqrt") values = result.values() expected = [1.0, 2.0, 3.0, 4.0] if values == expected: f_print_success(f"transform('sqrt'): {values} == {expected}") return True f_print_error(f"transform('sqrt'): {values} != {expected}") return False def test_pipe(): .. _example-series-add-87: .. dropdown:: add (test_series_phase4.py:36) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 26 :emphasize-lines: 11 import pandas as pd # ==================== Arithmetic Tests ==================== def test_add_scalar(): """Test Series add with scalar""" f_print_header("Test: Series add (scalar)") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.add(10.0) expected = [11.0, 12.0, 13.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("add (scalar): passed") return True except Exception as e: f_print_error(f"add (scalar) failed: {e}") return False def test_add_series(): .. _example-series-div-88: .. dropdown:: div (test_series_phase4.py:97) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 87 :emphasize-lines: 11 except Exception as e: f_print_error(f"mul (scalar) failed: {e}") return False def test_div_scalar(): """Test Series div with scalar""" f_print_header("Test: Series div (scalar)") try: s = pandasCore.Series([10.0, 20.0, 30.0]) result = s.div(2.0) expected = [5.0, 10.0, 15.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("div (scalar): passed") return True except Exception as e: f_print_error(f"div (scalar) failed: {e}") return False def test_truediv(): .. _example-series-floordiv-89: .. dropdown:: floordiv (test_series_phase4.py:127) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 117 :emphasize-lines: 11 except Exception as e: f_print_error(f"truediv failed: {e}") return False def test_floordiv(): """Test Series floordiv""" f_print_header("Test: Series floordiv") try: s = pandasCore.Series([10.0, 21.0, 35.0]) result = s.floordiv(4.0) expected = [2.0, 5.0, 8.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("floordiv: passed") return True except Exception as e: f_print_error(f"floordiv failed: {e}") return False def test_mod(): .. _example-series-mod-90: .. dropdown:: mod (test_series_phase4.py:142) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 132 :emphasize-lines: 11 except Exception as e: f_print_error(f"floordiv failed: {e}") return False def test_mod(): """Test Series mod""" f_print_header("Test: Series mod") try: s = pandasCore.Series([10.0, 21.0, 35.0]) result = s.mod(4.0) expected = [2.0, 1.0, 3.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("mod: passed") return True except Exception as e: f_print_error(f"mod failed: {e}") return False def test_pow(): .. _example-series-mul-91: .. dropdown:: mul (test_series_phase4.py:82) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 72 :emphasize-lines: 11 except Exception as e: f_print_error(f"sub (scalar) failed: {e}") return False def test_mul_scalar(): """Test Series mul with scalar""" f_print_header("Test: Series mul (scalar)") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.mul(2.0) expected = [2.0, 4.0, 6.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("mul (scalar): passed") return True except Exception as e: f_print_error(f"mul (scalar) failed: {e}") return False def test_div_scalar(): .. _example-series-pow-92: .. dropdown:: pow (test_series_phase4.py:157) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 147 :emphasize-lines: 11 except Exception as e: f_print_error(f"mod failed: {e}") return False def test_pow(): """Test Series pow""" f_print_header("Test: Series pow") try: s = pandasCore.Series([2.0, 3.0, 4.0]) result = s.pow(2.0) expected = [4.0, 9.0, 16.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("pow: passed") return True except Exception as e: f_print_error(f"pow failed: {e}") return False # ==================== Reverse Arithmetic Tests ==================== .. _example-series-radd-93: .. dropdown:: radd (test_series_phase4.py:174) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 164 :emphasize-lines: 11 return False # ==================== Reverse Arithmetic Tests ==================== def test_radd(): """Test Series radd""" f_print_header("Test: Series radd") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.radd(10.0) expected = [11.0, 12.0, 13.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("radd: passed") return True except Exception as e: f_print_error(f"radd failed: {e}") return False def test_rsub(): .. _example-series-rdiv-94: .. dropdown:: rdiv (test_series_phase4.py:219) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 209 :emphasize-lines: 11 except Exception as e: f_print_error(f"rmul failed: {e}") return False def test_rdiv(): """Test Series rdiv""" f_print_header("Test: Series rdiv") try: s = pandasCore.Series([1.0, 2.0, 4.0]) result = s.rdiv(8.0) # 8 / [1, 2, 4] = [8, 4, 2] expected = [8.0, 4.0, 2.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("rdiv: passed") return True except Exception as e: f_print_error(f"rdiv failed: {e}") return False def test_rfloordiv(): .. _example-series-rfloordiv-95: .. dropdown:: rfloordiv (test_series_phase4.py:234) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 224 :emphasize-lines: 11 except Exception as e: f_print_error(f"rdiv failed: {e}") return False def test_rfloordiv(): """Test Series rfloordiv""" f_print_header("Test: Series rfloordiv") try: s = pandasCore.Series([3.0, 4.0, 5.0]) result = s.rfloordiv(10.0) # 10 // [3, 4, 5] = [3, 2, 2] expected = [3.0, 2.0, 2.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("rfloordiv: passed") return True except Exception as e: f_print_error(f"rfloordiv failed: {e}") return False def test_rmod(): .. _example-series-rmod-96: .. dropdown:: rmod (test_series_phase4.py:249) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 239 :emphasize-lines: 11 except Exception as e: f_print_error(f"rfloordiv failed: {e}") return False def test_rmod(): """Test Series rmod""" f_print_header("Test: Series rmod") try: s = pandasCore.Series([3.0, 4.0, 5.0]) result = s.rmod(10.0) # 10 % [3, 4, 5] = [1, 2, 0] expected = [1.0, 2.0, 0.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("rmod: passed") return True except Exception as e: f_print_error(f"rmod failed: {e}") return False def test_rpow(): .. _example-series-rmul-97: .. dropdown:: rmul (test_series_phase4.py:204) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 194 :emphasize-lines: 11 except Exception as e: f_print_error(f"rsub failed: {e}") return False def test_rmul(): """Test Series rmul""" f_print_header("Test: Series rmul") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.rmul(5.0) expected = [5.0, 10.0, 15.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("rmul: passed") return True except Exception as e: f_print_error(f"rmul failed: {e}") return False def test_rdiv(): .. _example-series-rpow-98: .. dropdown:: rpow (test_series_phase4.py:264) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 254 :emphasize-lines: 11 except Exception as e: f_print_error(f"rmod failed: {e}") return False def test_rpow(): """Test Series rpow""" f_print_header("Test: Series rpow") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.rpow(2.0) # 2 ** [1, 2, 3] = [2, 4, 8] expected = [2.0, 4.0, 8.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("rpow: passed") return True except Exception as e: f_print_error(f"rpow failed: {e}") return False def test_divmod(): .. _example-series-rsub-99: .. dropdown:: rsub (test_series_phase4.py:189) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 179 :emphasize-lines: 11 except Exception as e: f_print_error(f"radd failed: {e}") return False def test_rsub(): """Test Series rsub""" f_print_header("Test: Series rsub") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.rsub(10.0) # 10 - [1, 2, 3] = [9, 8, 7] expected = [9.0, 8.0, 7.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("rsub: passed") return True except Exception as e: f_print_error(f"rsub failed: {e}") return False def test_rmul(): .. _example-series-sub-100: .. dropdown:: sub (test_series_phase4.py:67) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 57 :emphasize-lines: 11 except Exception as e: f_print_error(f"add (series) failed: {e}") return False def test_sub_scalar(): """Test Series sub with scalar""" f_print_header("Test: Series sub (scalar)") try: s = pandasCore.Series([10.0, 20.0, 30.0]) result = s.sub(5.0) expected = [5.0, 15.0, 25.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("sub (scalar): passed") return True except Exception as e: f_print_error(f"sub (scalar) failed: {e}") return False def test_mul_scalar(): .. _example-series-truediv-101: .. dropdown:: truediv (test_series_phase4.py:112) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 102 :emphasize-lines: 11 except Exception as e: f_print_error(f"div (scalar) failed: {e}") return False def test_truediv(): """Test Series truediv""" f_print_header("Test: Series truediv") try: s = pandasCore.Series([10.0, 20.0, 30.0]) result = s.truediv(4.0) expected = [2.5, 5.0, 7.5] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("truediv: passed") return True except Exception as e: f_print_error(f"truediv failed: {e}") return False def test_floordiv(): .. _example-series-eq-102: .. dropdown:: eq (test_series_phase4.py:408) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 398 :emphasize-lines: 11 except Exception as e: f_print_error(f"clip failed: {e}") return False def test_eq(): """Test Series eq""" f_print_header("Test: Series eq") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.eq(2.0) expected = [False, True, False] assert result == expected, f"Expected {expected}, got {result}" f_print_success("eq: passed") return True except Exception as e: f_print_error(f"eq failed: {e}") return False def test_ne(): .. _example-series-ge-103: .. dropdown:: ge (test_series_phase4.py:483) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 473 :emphasize-lines: 11 except Exception as e: f_print_error(f"gt failed: {e}") return False def test_ge(): """Test Series ge""" f_print_header("Test: Series ge") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.ge(2.0) expected = [False, True, True] assert result == expected, f"Expected {expected}, got {result}" f_print_success("ge: passed") return True except Exception as e: f_print_error(f"ge failed: {e}") return False def test_combine_first(): .. _example-series-gt-104: .. dropdown:: gt (test_series_phase4.py:468) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 458 :emphasize-lines: 11 except Exception as e: f_print_error(f"le failed: {e}") return False def test_gt(): """Test Series gt""" f_print_header("Test: Series gt") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.gt(2.0) expected = [False, False, True] assert result == expected, f"Expected {expected}, got {result}" f_print_success("gt: passed") return True except Exception as e: f_print_error(f"gt failed: {e}") return False def test_ge(): .. _example-series-le-105: .. dropdown:: le (test_series_phase4.py:453) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 443 :emphasize-lines: 11 except Exception as e: f_print_error(f"lt failed: {e}") return False def test_le(): """Test Series le""" f_print_header("Test: Series le") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.le(2.0) expected = [True, True, False] assert result == expected, f"Expected {expected}, got {result}" f_print_success("le: passed") return True except Exception as e: f_print_error(f"le failed: {e}") return False def test_gt(): .. _example-series-lt-106: .. dropdown:: lt (test_series_phase4.py:438) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 428 :emphasize-lines: 11 except Exception as e: f_print_error(f"ne failed: {e}") return False def test_lt(): """Test Series lt""" f_print_header("Test: Series lt") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.lt(2.0) expected = [True, False, False] assert result == expected, f"Expected {expected}, got {result}" f_print_success("lt: passed") return True except Exception as e: f_print_error(f"lt failed: {e}") return False def test_le(): .. _example-series-ne-107: .. dropdown:: ne (test_series_phase4.py:423) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 413 :emphasize-lines: 11 except Exception as e: f_print_error(f"eq failed: {e}") return False def test_ne(): """Test Series ne""" f_print_header("Test: Series ne") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.ne(2.0) expected = [True, False, True] assert result == expected, f"Expected {expected}, got {result}" f_print_success("ne: passed") return True except Exception as e: f_print_error(f"ne failed: {e}") return False def test_lt(): .. _example-series-argsort-108: .. dropdown:: argsort (test_series_phase5.py:89) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 79 :emphasize-lines: 11 def test_argsort(): """Test Series argsort method""" f_print_header("Test: Series argsort") try: s = pandasCore.Series([3.0, 1.0, 2.0], name="values") # argsort should return indices that would sort the array indices = s.argsort() # Original: [3, 1, 2] -> sorted: [1, 2, 3] -> indices: [1, 2, 0] assert indices == [1, 2, 0], f"argsort failed: {indices}" f_print_info(f" argsort([3,1,2]) = {indices}") f_print_success("Series argsort: passed") return True except Exception as e: f_print_error(f"Series argsort failed: {e}") return False .. _example-series-rank-109: .. dropdown:: rank (test_series_phase3.py:410) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 400 :emphasize-lines: 11 f_print_success(f"autocorr: {result}") return True f_print_error("autocorr: returned None") return False def test_rank(): """Test Series.rank()""" f_print_header("Test: rank") s = pandasCore.Series([3.0, 1.0, 4.0, 1.0, 5.0]) result = s.rank() values = result.values() # With method='average': 1.0 gets rank 1.5, 3.0 gets rank 3, 4.0 gets rank 4, 5.0 gets rank 5 f_print_success(f"rank: {values}") return True def test_nlargest(): """Test Series.nlargest()""" f_print_header("Test: nlargest") s = pandasCore.Series([3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0]) .. _example-series-searchsorted-110: .. dropdown:: searchsorted (test_series_phase3.py:587) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 577 :emphasize-lines: 11 f_print_success(f"last_valid_index: {result} == 2") return True f_print_error(f"last_valid_index: {result} != 2") return False def test_searchsorted(): """Test Series.searchsorted()""" f_print_header("Test: searchsorted") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.searchsorted(3.5) if result == 3: # 3.5 would be inserted at position 3 f_print_success(f"searchsorted(3.5): {result} == 3") return True f_print_error(f"searchsorted(3.5): {result} != 3") return False def f_main(): """Main test function""" # Run tests .. _example-series-sort_index-111: .. dropdown:: sort_index (test_series_phase5.py:67) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 57 :emphasize-lines: 11 def test_sort_index(): """Test Series sort_index method""" f_print_header("Test: Series sort_index") try: # Create series with custom index (in reverse order) s = pandasCore.Series([3.0, 2.0, 1.0], name="values") # Test ascending sort sorted_s = s.sort_index() f_print_info(f" Sort index result: {sorted_s.to_list()}") # Test descending sort sorted_s = s.sort_index(ascending=False) f_print_info(f" Sort index descending: {sorted_s.to_list()}") f_print_success("Series sort_index: passed") return True except Exception as e: f_print_error(f"Series sort_index failed: {e}") .. _example-series-sort_values-112: .. dropdown:: sort_values (test_series_phase5.py:40) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 30 :emphasize-lines: 11 # ============================================================================ def test_sort_values(): """Test Series sort_values method""" f_print_header("Test: Series sort_values") try: s = pandasCore.Series([3.0, 1.0, 2.0, 5.0, 4.0], name="values") # Test ascending sort (default) sorted_s = s.sort_values() values = sorted_s.to_list() assert values == [1.0, 2.0, 3.0, 4.0, 5.0], f"Ascending sort failed: {values}" f_print_info(" Ascending sort: OK") # Test descending sort sorted_s = s.sort_values(ascending=False) values = sorted_s.to_list() assert values == [5.0, 4.0, 3.0, 2.0, 1.0], f"Descending sort failed: {values}" f_print_info(" Descending sort: OK") .. _example-series-explode-113: .. dropdown:: explode (test_series_phase4.py:517) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 507 :emphasize-lines: 11 except Exception as e: f_print_error(f"combine_first failed: {e}") return False def test_explode(): """Test Series explode""" f_print_header("Test: Series explode") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.explode() # For scalar types, explode returns same series assert result.to_list() == [1.0, 2.0, 3.0], "explode should return same values for scalars" f_print_success("explode: passed") return True except Exception as e: f_print_error(f"explode failed: {e}") return False def test_repeat(): .. _example-series-swapaxes-114: .. dropdown:: swapaxes (test_series_phase5.py:252) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 242 :emphasize-lines: 11 def test_swapaxes(): """Test Series swapaxes method""" f_print_header("Test: Series swapaxes") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # swapaxes is no-op for Series result = s.swapaxes(0, 0) assert result.to_list() == s.to_list(), "swapaxes should return same values" f_print_info(f" swapaxes(0, 0): {result.to_list()}") f_print_success("Series swapaxes: passed") return True except Exception as e: f_print_error(f"Series swapaxes failed: {e}") return False .. _example-series-to_frame-115: .. dropdown:: to_frame (test_series.py:309) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 299 :emphasize-lines: 11 def test_series_to_frame(): """Test Series to_frame method""" f_print_header("Test: Series to_frame") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") # Convert to DataFrame df = s.to_frame() assert df is not None, "to_frame should return DataFrame" assert len(df) == 3, f"DataFrame should have 3 rows, got {len(df)}" # With custom column name df2 = s.to_frame(name="custom") assert df2 is not None, "to_frame with name should return DataFrame" f_print_success("Series to_frame: passed") return True except Exception as e: .. _example-series-transpose-116: .. dropdown:: transpose (test_series_phase5.py:209) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 199 :emphasize-lines: 11 def test_transpose(): """Test Series transpose method""" f_print_header("Test: Series transpose") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # transpose is no-op for Series transposed = s.transpose() assert transposed.to_list() == s.to_list(), "transpose should return same values" f_print_info(f" transpose(): {transposed.to_list()}") # T property transposed = s.T assert transposed.to_list() == s.to_list(), "T property should return same values" f_print_info(f" .T property: {transposed.to_list()}") f_print_success("Series transpose: passed") return True .. _example-series-unstack-117: .. dropdown:: unstack (test_series_phase5.py:271) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 261 :emphasize-lines: 11 def test_unstack(): """Test Series unstack method""" f_print_header("Test: Series unstack") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") # unstack returns DataFrame result = s.unstack() # Result should be a DataFrame (check for DataFrame-specific attributes) # Note: ncols is a method, not an attribute, in pandasCore is_dataframe = hasattr(result, 'columns') or hasattr(result, 'nrows') assert is_dataframe, "unstack should return DataFrame" f_print_info(f" unstack(): returned DataFrame") f_print_success("Series unstack: passed") return True except Exception as e: f_print_error(f"Series unstack failed: {e}") .. _example-series-asfreq-118: .. dropdown:: asfreq (test_series_phase5.py:404) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 394 :emphasize-lines: 11 # ============================================================================ def test_time_series_placeholders(): """Test Series time series placeholders""" f_print_header("Test: Series time series placeholders") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # asfreq returns copy - use positional argument (pybind11 requirement) result = s.asfreq("D") assert len(result) == 3, "asfreq should return copy" f_print_info(" asfreq: returns copy") # at_time returns copy result = s.at_time(time="09:30") assert len(result) == 3, "at_time should return copy" f_print_info(" at_time: returns copy") # between_time returns copy result = s.between_time(start_time="09:00", end_time="17:00") .. _example-series-asof-119: .. dropdown:: asof (test_series_phase5.py:528) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 518 :emphasize-lines: 11 def test_asof(): """Test Series asof method""" f_print_header("Test: Series asof") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # asof returns last value result = s.asof("5") assert result == 5.0, f"asof should return last value, got {result}" f_print_info(f" asof('5'): {result}") f_print_success("Series asof: passed") return True except Exception as e: f_print_error(f"Series asof failed: {e}") return False .. _example-series-at_time-120: .. dropdown:: at_time (test_series_phase5.py:409) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 399 :emphasize-lines: 11 try: s = pandasCore.Series([1.0, 2.0, 3.0]) # asfreq returns copy - use positional argument (pybind11 requirement) result = s.asfreq("D") assert len(result) == 3, "asfreq should return copy" f_print_info(" asfreq: returns copy") # at_time returns copy result = s.at_time(time="09:30") assert len(result) == 3, "at_time should return copy" f_print_info(" at_time: returns copy") # between_time returns copy result = s.between_time(start_time="09:00", end_time="17:00") assert len(result) == 3, "between_time should return copy" f_print_info(" between_time: returns copy") # tz_localize returns copy result = s.tz_localize(tz="UTC") .. _example-series-between_time-121: .. dropdown:: between_time (test_series_phase5.py:414) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 404 :emphasize-lines: 11 result = s.asfreq("D") assert len(result) == 3, "asfreq should return copy" f_print_info(" asfreq: returns copy") # at_time returns copy result = s.at_time(time="09:30") assert len(result) == 3, "at_time should return copy" f_print_info(" at_time: returns copy") # between_time returns copy result = s.between_time(start_time="09:00", end_time="17:00") assert len(result) == 3, "between_time should return copy" f_print_info(" between_time: returns copy") # tz_localize returns copy result = s.tz_localize(tz="UTC") assert len(result) == 3, "tz_localize should return copy" f_print_info(" tz_localize: returns copy") # tz_convert returns copy result = s.tz_convert(tz="US/Eastern") .. _example-series-diff-122: .. dropdown:: diff (test_series_phase3.py:343) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 333 :emphasize-lines: 11 f_print_success(f"cummax: {values} == {expected}") return True f_print_error(f"cummax: {values} != {expected}") return False def test_diff(): """Test Series.diff()""" f_print_header("Test: diff") s = pandasCore.Series([1.0, 2.0, 4.0, 7.0, 11.0]) result = s.diff() values = result.values() # First value should be NaN, rest are differences if math.isnan(values[0]) and values[1:] == [1.0, 2.0, 3.0, 4.0]: f_print_success(f"diff: first is NaN, rest are [1.0, 2.0, 3.0, 4.0]") return True f_print_error(f"diff: unexpected values {values}") return False def test_pct_change(): .. _example-series-first_valid_index-123: .. dropdown:: first_valid_index (test_series_phase3.py:563) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 553 :emphasize-lines: 11 f_print_success(f"any: {result} (has one non-zero)") return True f_print_error(f"any: {result} != True") return False def test_first_valid_index(): """Test Series.first_valid_index()""" f_print_header("Test: first_valid_index") s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.first_valid_index() if result == 0: f_print_success(f"first_valid_index: {result} == 0") return True f_print_error(f"first_valid_index: {result} != 0") return False def test_last_valid_index(): """Test Series.last_valid_index()""" f_print_header("Test: last_valid_index") .. _example-series-last_valid_index-124: .. dropdown:: last_valid_index (test_series_phase3.py:575) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 565 :emphasize-lines: 11 f_print_success(f"first_valid_index: {result} == 0") return True f_print_error(f"first_valid_index: {result} != 0") return False def test_last_valid_index(): """Test Series.last_valid_index()""" f_print_header("Test: last_valid_index") s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.last_valid_index() if result == 2: f_print_success(f"last_valid_index: {result} == 2") return True f_print_error(f"last_valid_index: {result} != 2") return False def test_searchsorted(): """Test Series.searchsorted()""" f_print_header("Test: searchsorted") .. _example-series-pct_change-125: .. dropdown:: pct_change (test_series_phase3.py:357) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 347 :emphasize-lines: 11 f_print_success(f"diff: first is NaN, rest are [1.0, 2.0, 3.0, 4.0]") return True f_print_error(f"diff: unexpected values {values}") return False def test_pct_change(): """Test Series.pct_change()""" f_print_header("Test: pct_change") s = pandasCore.Series([100.0, 110.0, 121.0]) result = s.pct_change() values = result.values() # First should be NaN, second is 0.1, third is 0.1 if math.isnan(values[0]) and abs(values[1] - 0.1) < 1e-10 and abs(values[2] - 0.1) < 1e-10: f_print_success(f"pct_change: NaN, 0.1, 0.1") return True f_print_error(f"pct_change: unexpected values {values}") return False def test_corr(): .. _example-series-shift-126: .. dropdown:: shift (test_series_phase5.py:113) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 103 :emphasize-lines: 11 # ============================================================================ def test_shift(): """Test Series shift method""" f_print_header("Test: Series shift") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Shift forward by 1 shifted = s.shift(1) values = shifted.to_list() # First element should be NaN or some fill value (implementation dependent) assert values[1:] == [1.0, 2.0, 3.0, 4.0], f"Shift(1) failed: {values}" f_print_info(f" shift(1): {values[:5]}") # Shift backward by 1 shifted = s.shift(-1) values = shifted.to_list() assert values[:4] == [2.0, 3.0, 4.0, 5.0], f"Shift(-1) failed: {values}" f_print_info(f" shift(-1): {values[:5]}") .. _example-series-to_period-127: .. dropdown:: to_period (test_series_phase5.py:429) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 419 :emphasize-lines: 11 result = s.tz_localize(tz="UTC") assert len(result) == 3, "tz_localize should return copy" f_print_info(" tz_localize: returns copy") # tz_convert returns copy result = s.tz_convert(tz="US/Eastern") assert len(result) == 3, "tz_convert should return copy" f_print_info(" tz_convert: returns copy") # to_period returns copy result = s.to_period() assert len(result) == 3, "to_period should return copy" f_print_info(" to_period: returns copy") # to_timestamp returns copy result = s.to_timestamp() assert len(result) == 3, "to_timestamp should return copy" f_print_info(" to_timestamp: returns copy") f_print_success("Series time series placeholders: passed") return True .. _example-series-to_timestamp-128: .. dropdown:: to_timestamp (test_series_phase5.py:434) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 424 :emphasize-lines: 11 result = s.tz_convert(tz="US/Eastern") assert len(result) == 3, "tz_convert should return copy" f_print_info(" tz_convert: returns copy") # to_period returns copy result = s.to_period() assert len(result) == 3, "to_period should return copy" f_print_info(" to_period: returns copy") # to_timestamp returns copy result = s.to_timestamp() assert len(result) == 3, "to_timestamp should return copy" f_print_info(" to_timestamp: returns copy") f_print_success("Series time series placeholders: passed") return True except Exception as e: f_print_error(f"Series time series placeholders failed: {e}") return False .. _example-series-tz_convert-129: .. dropdown:: tz_convert (test_series_phase5.py:424) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 414 :emphasize-lines: 11 result = s.between_time(start_time="09:00", end_time="17:00") assert len(result) == 3, "between_time should return copy" f_print_info(" between_time: returns copy") # tz_localize returns copy result = s.tz_localize(tz="UTC") assert len(result) == 3, "tz_localize should return copy" f_print_info(" tz_localize: returns copy") # tz_convert returns copy result = s.tz_convert(tz="US/Eastern") assert len(result) == 3, "tz_convert should return copy" f_print_info(" tz_convert: returns copy") # to_period returns copy result = s.to_period() assert len(result) == 3, "to_period should return copy" f_print_info(" to_period: returns copy") # to_timestamp returns copy result = s.to_timestamp() .. _example-series-tz_localize-130: .. dropdown:: tz_localize (test_series_phase5.py:419) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 409 :emphasize-lines: 11 result = s.at_time(time="09:30") assert len(result) == 3, "at_time should return copy" f_print_info(" at_time: returns copy") # between_time returns copy result = s.between_time(start_time="09:00", end_time="17:00") assert len(result) == 3, "between_time should return copy" f_print_info(" between_time: returns copy") # tz_localize returns copy result = s.tz_localize(tz="UTC") assert len(result) == 3, "tz_localize should return copy" f_print_info(" tz_localize: returns copy") # tz_convert returns copy result = s.tz_convert(tz="US/Eastern") assert len(result) == 3, "tz_convert should return copy" f_print_info(" tz_convert: returns copy") # to_period returns copy result = s.to_period() .. _example-series-to_csv-131: .. dropdown:: to_csv (test_series_phase4.py:549) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 539 :emphasize-lines: 11 return False # ==================== I/O Tests ==================== def test_to_csv(): """Test Series to_csv""" f_print_header("Test: Series to_csv") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") csv_str = s.to_csv() assert isinstance(csv_str, str), "to_csv should return a string" assert "1" in csv_str, "CSV should contain value 1" assert "2" in csv_str, "CSV should contain value 2" f_print_success("to_csv: passed") return True except Exception as e: f_print_error(f"to_csv failed: {e}") return False .. _example-series-to_dict-132: .. dropdown:: to_dict (test_series_phase4.py:625) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 615 :emphasize-lines: 11 except Exception as e: f_print_error(f"to_latex failed: {e}") return False def test_to_dict(): """Test Series to_dict""" f_print_header("Test: Series to_dict") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.to_dict() assert isinstance(result, dict), "to_dict should return a dict" assert len(result) == 3, f"Expected 3 items, got {len(result)}" f_print_success("to_dict: passed") return True except Exception as e: f_print_error(f"to_dict failed: {e}") return False def test_tolist(): .. _example-series-to_json-133: .. dropdown:: to_json (test_series_phase4.py:565) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 555 :emphasize-lines: 11 except Exception as e: f_print_error(f"to_csv failed: {e}") return False def test_to_json(): """Test Series to_json""" f_print_header("Test: Series to_json") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") json_str = s.to_json() assert isinstance(json_str, str), "to_json should return a string" # JSON should have values assert "1" in json_str, "JSON should contain value 1" f_print_success("to_json: passed") return True except Exception as e: f_print_error(f"to_json failed: {e}") return False .. _example-series-to_latex-134: .. dropdown:: to_latex (test_series_phase4.py:610) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 600 :emphasize-lines: 11 except Exception as e: f_print_error(f"to_markdown failed: {e}") return False def test_to_latex(): """Test Series to_latex""" f_print_header("Test: Series to_latex") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") latex_str = s.to_latex() assert isinstance(latex_str, str), "to_latex should return a string" assert "tabular" in latex_str or "begin" in latex_str, "LaTeX should contain tabular" f_print_success("to_latex: passed") return True except Exception as e: f_print_error(f"to_latex failed: {e}") return False def test_to_dict(): .. _example-series-to_list-135: .. dropdown:: to_list (test_series.py:104) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 94 :emphasize-lines: 11 def test_series_copy(): """Test Series copy method""" f_print_header("Test: Series copy") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="original") # Test deep copy (default) s_copy = s.copy() assert s_copy.to_list() == s.to_list(), "Deep copy values differ" assert s_copy.name == s.name, "Deep copy name differs" # Test shallow copy s_shallow = s.copy(deep=False) assert s_shallow.to_list() == s.to_list(), "Shallow copy values differ" f_print_success("Series copy: passed") return True except Exception as e: f_print_error(f"Series copy failed: {e}") .. _example-series-to_markdown-136: .. dropdown:: to_markdown (test_series_phase4.py:595) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 585 :emphasize-lines: 11 except Exception as e: f_print_error(f"to_string failed: {e}") return False def test_to_markdown(): """Test Series to_markdown""" f_print_header("Test: Series to_markdown") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") md_str = s.to_markdown() assert isinstance(md_str, str), "to_markdown should return a string" assert "|" in md_str, "Markdown should contain table separators" f_print_success("to_markdown: passed") return True except Exception as e: f_print_error(f"to_markdown failed: {e}") return False def test_to_latex(): .. _example-series-to_numpy-137: .. dropdown:: to_numpy (test_series_phase4.py:655) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 645 :emphasize-lines: 11 except Exception as e: f_print_error(f"tolist failed: {e}") return False def test_to_numpy(): """Test Series to_numpy""" f_print_header("Test: Series to_numpy") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.to_numpy() # Returns list in our implementation assert result == [1.0, 2.0, 3.0], f"Expected [1.0, 2.0, 3.0], got {result}" f_print_success("to_numpy: passed") return True except Exception as e: f_print_error(f"to_numpy failed: {e}") return False def test_align(): .. _example-series-to_string-138: .. dropdown:: to_string (test_series_phase4.py:581) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 571 :emphasize-lines: 11 except Exception as e: f_print_error(f"to_json failed: {e}") return False def test_to_string(): """Test Series to_string""" f_print_header("Test: Series to_string") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="values") str_result = s.to_string() assert isinstance(str_result, str), "to_string should return a string" f_print_success("to_string: passed") return True except Exception as e: f_print_error(f"to_string failed: {e}") return False def test_to_markdown(): """Test Series to_markdown""" .. _example-series-tolist-139: .. dropdown:: tolist (test_series_phase4.py:640) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 630 :emphasize-lines: 11 except Exception as e: f_print_error(f"to_dict failed: {e}") return False def test_tolist(): """Test Series tolist (alias)""" f_print_header("Test: Series tolist") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.tolist() expected = [1.0, 2.0, 3.0] assert result == expected, f"Expected {expected}, got {result}" f_print_success("tolist: passed") return True except Exception as e: f_print_error(f"tolist failed: {e}") return False def test_to_numpy(): .. _example-series-astype-140: .. dropdown:: astype (test_series_phase5.py:190) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 180 :emphasize-lines: 11 def test_astype(): """Test Series astype method""" f_print_header("Test: Series astype") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # astype returns copy for float64 series result = s.astype("int64") assert len(result) == 3, f"astype result length incorrect" f_print_info(f" astype('int64'): {result.to_list()}") f_print_success("Series astype: passed") return True except Exception as e: f_print_error(f"Series astype failed: {e}") return False .. _example-series-bool-141: .. dropdown:: bool (test_missing_methods.py:77) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 67 :emphasize-lines: 11 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") result = s.bool() assert result == True, f"Expected True, got {result}" def test_series_bool_int(): """Test IntSeries.bool (deprecated)""" global tests_run tests_run += 1 s = pandasCore.IntSeries([1]) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") .. _example-series-convert_dtypes-142: .. dropdown:: convert_dtypes (test_series_phase5.py:547) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 537 :emphasize-lines: 11 def test_convert_dtypes(): """Test Series convert_dtypes method""" f_print_header("Test: Series convert_dtypes") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # convert_dtypes returns copy for float64 result = s.convert_dtypes() assert result.to_list() == s.to_list(), "convert_dtypes should return same values" f_print_info(f" convert_dtypes(): {result.to_list()}") f_print_success("Series convert_dtypes: passed") return True except Exception as e: f_print_error(f"Series convert_dtypes failed: {e}") return False .. _example-series-copy-143: .. dropdown:: copy (test_series.py:103) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 93 :emphasize-lines: 11 def test_series_copy(): """Test Series copy method""" f_print_header("Test: Series copy") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="original") # Test deep copy (default) s_copy = s.copy() assert s_copy.to_list() == s.to_list(), "Deep copy values differ" assert s_copy.name == s.name, "Deep copy name differs" # Test shallow copy s_shallow = s.copy(deep=False) assert s_shallow.to_list() == s.to_list(), "Shallow copy values differ" f_print_success("Series copy: passed") return True except Exception as e: .. _example-series-infer_objects-144: .. dropdown:: infer_objects (test_series_phase5.py:566) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 556 :emphasize-lines: 11 def test_infer_objects(): """Test Series infer_objects method""" f_print_header("Test: Series infer_objects") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # infer_objects returns copy result = s.infer_objects() assert result.to_list() == s.to_list(), "infer_objects should return same values" f_print_info(f" infer_objects(): {result.to_list()}") f_print_success("Series infer_objects: passed") return True except Exception as e: f_print_error(f"Series infer_objects failed: {e}") return False .. _example-series-view-145: .. dropdown:: view (test_series.py:373) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 363 :emphasize-lines: 11 def test_series_view(): """Test Series view method""" f_print_header("Test: Series view") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # view returns shallow copy s_view = s.view() assert s_view.to_list() == s.to_list(), "View should have same values" f_print_success("Series view: passed") return True except Exception as e: f_print_error(f"Series view failed: {e}") return False def test_series_len(): .. _example-series-items-146: .. dropdown:: items (test_series.py:143) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 133 :emphasize-lines: 11 f_print_error(f"Series keys failed: {e}") return False def test_series_items(): """Test Series items method""" f_print_header("Test: Series items") try: s = pandasCore.Series([1.0, 2.0, 3.0]) items = s.items() # Should return list of (index, value) tuples assert len(items) == 3, f"Expected 3 items, got {len(items)}" assert items[0] == ("0", 1.0), f"First item incorrect: {items[0]}" assert items[1] == ("1", 2.0), f"Second item incorrect: {items[1]}" assert items[2] == ("2", 3.0), f"Third item incorrect: {items[2]}" f_print_success("Series items: passed") return True except Exception as e: .. _example-series-keys-147: .. dropdown:: keys (test_series.py:124) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 114 :emphasize-lines: 11 f_print_error(f"Series copy failed: {e}") return False def test_series_keys(): """Test Series keys method""" f_print_header("Test: Series keys") try: s = pandasCore.Series([1.0, 2.0, 3.0]) keys = s.keys() # Default RangeIndex should give us ["0", "1", "2"] assert len(keys) == 3, f"Expected 3 keys, got {len(keys)}" assert keys == ["0", "1", "2"], f"Expected ['0', '1', '2'], got {keys}" f_print_success("Series keys: passed") return True except Exception as e: f_print_error(f"Series keys failed: {e}") return False .. _example-series-drop_duplicates-148: .. dropdown:: drop_duplicates (test_series_phase2.py:223) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 213 :emphasize-lines: 11 def test_drop_duplicates(): """Test Series drop_duplicates method""" f_print_header("Test: Series drop_duplicates") try: s = pandasCore.Series([1.0, 2.0, 2.0, 3.0, 3.0, 3.0]) # Drop duplicates keeping first s_unique = s.drop_duplicates(keep="first") assert len(s_unique) == 3, f"Expected 3 unique values, got {len(s_unique)}" assert s_unique.to_list() == [1.0, 2.0, 3.0], f"Values incorrect: {s_unique.to_list()}" f_print_success("drop_duplicates: passed") return True except Exception as e: f_print_error(f"drop_duplicates failed: {e}") return False .. _example-series-duplicated-149: .. dropdown:: duplicated (test_series_phase2.py:242) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 232 :emphasize-lines: 11 def test_duplicated(): """Test Series duplicated method""" f_print_header("Test: Series duplicated") try: s = pandasCore.Series([1.0, 2.0, 2.0, 3.0]) # Get duplicated mask dup_mask = s.duplicated() assert len(dup_mask) == 4, f"Expected 4 elements, got {len(dup_mask)}" # First 2.0 is not duplicate, second is assert dup_mask == [False, False, True, False], f"Unexpected mask: {dup_mask}" f_print_success("duplicated: passed") return True except Exception as e: f_print_error(f"duplicated failed: {e}") return False .. _example-series-isin-150: .. dropdown:: isin (test_series_phase2.py:624) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 614 :emphasize-lines: 11 def test_isin(): """Test Series isin method""" f_print_header("Test: Series isin") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Check membership result = s.isin([2.0, 4.0]) expected = [False, True, False, True, False] assert result == expected, f"Expected {expected}, got {result}" f_print_success("isin: passed") return True except Exception as e: f_print_error(f"isin failed: {e}") return False .. _example-series-unique-151: .. dropdown:: unique (test_series_phase2.py:699) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 689 :emphasize-lines: 11 return False def test_unique(): """Test Series unique method""" f_print_header("Test: Series unique") try: s = pandasCore.Series([1.0, 2.0, 2.0, 3.0, 1.0, 3.0]) result = s.unique() # Unique values in order of first appearance assert len(result) == 3, f"Expected 3 unique values, got {len(result)}" assert set(result) == {1.0, 2.0, 3.0}, f"Unexpected unique values: {result}" f_print_success("unique: passed") return True except Exception as e: f_print_error(f"unique failed: {e}") return False .. _example-series-round-152: .. dropdown:: round (test_series_phase4.py:372) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 362 :emphasize-lines: 11 return False def test_round(): """Test Series round""" f_print_header("Test: Series round") try: s = pandasCore.Series([1.234, 2.567, 3.891]) # Round to 0 decimals result = s.round(0) expected = [1.0, 3.0, 4.0] assert result.to_list() == expected, f"round(0): Expected {expected}, got {result.to_list()}" # Round to 2 decimals result = s.round(2) expected = [1.23, 2.57, 3.89] assert result.to_list() == expected, f"round(2): Expected {expected}, got {result.to_list()}" f_print_success("round: passed") return True .. _example-series-abs-153: .. dropdown:: abs (test_series_phase4.py:355) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 345 :emphasize-lines: 11 return False # ==================== Comparison & Other Tests ==================== def test_abs(): """Test Series abs""" f_print_header("Test: Series abs") try: s = pandasCore.Series([-1.0, 2.0, -3.0, 4.0]) result = s.abs() expected = [1.0, 2.0, 3.0, 4.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("abs: passed") return True except Exception as e: f_print_error(f"abs failed: {e}") return False def test_round(): .. _example-series-add_prefix-154: .. dropdown:: add_prefix (test_series_phase2.py:120) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 110 :emphasize-lines: 11 def test_add_prefix(): """Test Series add_prefix method""" f_print_header("Test: Series add_prefix") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # Add prefix to index labels s_prefixed = s.add_prefix("item_") keys = s_prefixed.keys() assert keys[0] == "item_0", f"Expected 'item_0', got {keys[0]}" assert keys[1] == "item_1", f"Expected 'item_1', got {keys[1]}" f_print_success("add_prefix: passed") return True except Exception as e: f_print_error(f"add_prefix failed: {e}") return False .. _example-series-add_suffix-155: .. dropdown:: add_suffix (test_series_phase2.py:140) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 130 :emphasize-lines: 11 def test_add_suffix(): """Test Series add_suffix method""" f_print_header("Test: Series add_suffix") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # Add suffix to index labels s_suffixed = s.add_suffix("_item") keys = s_suffixed.keys() assert keys[0] == "0_item", f"Expected '0_item', got {keys[0]}" assert keys[1] == "1_item", f"Expected '1_item', got {keys[1]}" f_print_success("add_suffix: passed") return True except Exception as e: f_print_error(f"add_suffix failed: {e}") return False .. _example-series-all-156: .. dropdown:: all (test_series_phase3.py:539) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 529 :emphasize-lines: 11 f_print_success(f"pipe(double_sum): {result} == 30.0") return True f_print_error(f"pipe(double_sum): {result} != 30.0") return False def test_all(): """Test Series.all()""" f_print_header("Test: all") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.all() if result == True: f_print_success(f"all: {result} (all non-zero)") return True f_print_error(f"all: {result} != True") return False def test_any(): """Test Series.any()""" f_print_header("Test: any") .. _example-series-any-157: .. dropdown:: any (test_series_phase3.py:551) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 541 :emphasize-lines: 11 f_print_success(f"all: {result} (all non-zero)") return True f_print_error(f"all: {result} != True") return False def test_any(): """Test Series.any()""" f_print_header("Test: any") s = pandasCore.Series([0.0, 0.0, 0.0, 1.0, 0.0]) result = s.any() if result == True: f_print_success(f"any: {result} (has one non-zero)") return True f_print_error(f"any: {result} != True") return False def test_first_valid_index(): """Test Series.first_valid_index()""" f_print_header("Test: first_valid_index") .. _example-series-argmax-158: .. dropdown:: argmax (test_series_phase3.py:263) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 253 :emphasize-lines: 11 result = s.idxmin() # Index of 1.0 is "1" (position 1) f_print_success(f"idxmin: {result}") return True def test_argmax(): """Test Series.argmax()""" f_print_header("Test: argmax") s = pandasCore.Series([3.0, 1.0, 5.0, 2.0, 4.0]) result = s.argmax() if result == 2: # Position of 5.0 f_print_success(f"argmax: {result} == 2") return True f_print_error(f"argmax: {result} != 2") return False def test_argmin(): """Test Series.argmin()""" f_print_header("Test: argmin") .. _example-series-argmin-159: .. dropdown:: argmin (test_series_phase3.py:275) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 265 :emphasize-lines: 11 f_print_success(f"argmax: {result} == 2") return True f_print_error(f"argmax: {result} != 2") return False def test_argmin(): """Test Series.argmin()""" f_print_header("Test: argmin") s = pandasCore.Series([3.0, 1.0, 5.0, 2.0, 4.0]) result = s.argmin() if result == 1: # Position of 1.0 f_print_success(f"argmin: {result} == 1") return True f_print_error(f"argmin: {result} != 1") return False def test_cumsum(): """Test Series.cumsum()""" f_print_header("Test: cumsum") .. _example-series-autocorr-160: .. dropdown:: autocorr (test_series_phase3.py:398) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 388 :emphasize-lines: 11 f_print_success(f"cov: {result} > 0") return True f_print_error(f"cov: {result} not positive") return False def test_autocorr(): """Test Series.autocorr()""" f_print_header("Test: autocorr") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.autocorr(1) if result is not None: f_print_success(f"autocorr: {result}") return True f_print_error("autocorr: returned None") return False def test_rank(): """Test Series.rank()""" f_print_header("Test: rank") .. _example-series-between-161: .. dropdown:: between (test_series_phase2.py:643) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 633 :emphasize-lines: 11 def test_between(): """Test Series between method""" f_print_header("Test: Series between") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Check if values are between 2 and 4 (inclusive) result = s.between(2.0, 4.0, inclusive="both") expected = [False, True, True, True, False] assert result == expected, f"Expected {expected}, got {result}" # Test exclusive result = s.between(2.0, 4.0, inclusive="neither") expected = [False, False, True, False, False] assert result == expected, f"Expected {expected}, got {result}" f_print_success("between: passed") return True .. _example-series-case_when-162: .. dropdown:: case_when (test_series_phase2.py:674) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 664 :emphasize-lines: 11 try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Apply case_when with conditions # In pandasCore, unmatched values become NaN (no default_value parameter) caselist = [ ([True, False, False, False, False], 10.0), ([False, True, True, False, False], 20.0), ] result = s.case_when(caselist) result_list = result.to_list() # First element: matches first condition -> 10.0 # Second, third: match second condition -> 20.0 # Fourth, fifth: no match -> NaN (pandasCore behavior) assert result_list[0] == 10.0, f"First element should be 10.0, got {result_list[0]}" assert result_list[1] == 20.0, f"Second element should be 20.0, got {result_list[1]}" assert result_list[2] == 20.0, f"Third element should be 20.0, got {result_list[2]}" assert math.isnan(result_list[3]), f"Fourth element should be NaN, got {result_list[3]}" assert math.isnan(result_list[4]), f"Fifth element should be NaN, got {result_list[4]}" .. _example-series-clip-163: .. dropdown:: clip (test_series_phase4.py:393) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 383 :emphasize-lines: 11 except Exception as e: f_print_error(f"round failed: {e}") return False def test_clip(): """Test Series clip""" f_print_header("Test: Series clip") try: s = pandasCore.Series([1.0, 5.0, 10.0, 15.0, 20.0]) result = s.clip(5.0, 15.0) expected = [5.0, 5.0, 10.0, 15.0, 15.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("clip: passed") return True except Exception as e: f_print_error(f"clip failed: {e}") return False def test_eq(): .. _example-series-divide-164: .. dropdown:: divide (test_series_phase4.py:338) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 328 :emphasize-lines: 11 # Test subtract result = s.subtract(5.0) assert result.to_list() == [5.0, 15.0, 25.0], "subtract failed" # Test multiply result = s.multiply(2.0) assert result.to_list() == [20.0, 40.0, 60.0], "multiply failed" # Test divide result = s.divide(2.0) assert result.to_list() == [5.0, 10.0, 15.0], "divide failed" f_print_success("arithmetic aliases: passed") return True except Exception as e: f_print_error(f"arithmetic aliases failed: {e}") return False # ==================== Comparison & Other Tests ==================== .. _example-series-divmod-165: .. dropdown:: divmod (test_series_phase4.py:279) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 269 :emphasize-lines: 11 except Exception as e: f_print_error(f"rpow failed: {e}") return False def test_divmod(): """Test Series divmod""" f_print_header("Test: Series divmod") try: s = pandasCore.Series([10.0, 21.0, 35.0]) quot, rem = s.divmod(4.0) expected_quot = [2.0, 5.0, 8.0] expected_rem = [2.0, 1.0, 3.0] assert quot.to_list() == expected_quot, f"Expected quot {expected_quot}, got {quot.to_list()}" assert rem.to_list() == expected_rem, f"Expected rem {expected_rem}, got {rem.to_list()}" f_print_success("divmod: passed") return True except Exception as e: f_print_error(f"divmod failed: {e}") return False .. _example-series-factorize-166: .. dropdown:: factorize (test_series_phase2.py:740) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 730 :emphasize-lines: 11 return False def test_factorize(): """Test Series factorize method""" f_print_header("Test: Series factorize") try: s = pandasCore.Series([3.0, 1.0, 2.0, 1.0, 3.0]) codes, uniques = s.factorize() # Check codes are valid indices assert len(codes) == 5, f"Expected 5 codes, got {len(codes)}" assert len(uniques) == 3, f"Expected 3 unique values, got {len(uniques)}" # Codes should map back to original values for i, code in enumerate(codes): if code >= 0: # Not NaN assert uniques[code] == s[i], f"Code {code} doesn't map to correct value" .. _example-series-filter-167: .. dropdown:: filter (test_series_phase5.py:168) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 158 :emphasize-lines: 11 def test_filter(): """Test Series filter method""" f_print_header("Test: Series filter") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Filter by items filtered = s.filter(items=["0", "2", "4"]) f_print_info(f" filter(items=['0','2','4']): {filtered.to_list()}") # Filter by like (substring match) filtered = s.filter(like="1") f_print_info(f" filter(like='1'): {filtered.to_list()}") f_print_success("Series filter: passed") return True except Exception as e: f_print_error(f"Series filter failed: {e}") .. _example-series-hist-168: .. dropdown:: hist (test_series_phase5.py:645) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 635 :emphasize-lines: 11 def test_hist_placeholder(): """Test Series hist placeholder""" f_print_header("Test: Series hist (placeholder)") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # hist should raise error try: s.hist() f_print_error("hist should raise error") return False except RuntimeError as e: assert "matplotlib" in str(e).lower(), f"Wrong error message: {e}" f_print_info(" hist raises expected matplotlib error") f_print_success("Series hist placeholder: passed") return True except Exception as e: f_print_error(f"Series hist placeholder failed: {e}") .. _example-series-info-169: .. dropdown:: info (test_series.py:188) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 178 :emphasize-lines: 11 def test_series_info(): """Test Series info method""" f_print_header("Test: Series info") try: s = pandasCore.Series([1.0, 2.0, 3.0], name="test") # info() prints to stdout, just verify it doesn't raise s.info() f_print_success("Series info: passed") return True except Exception as e: f_print_error(f"Series info failed: {e}") return False def test_series_memory_usage(): """Test Series memory_usage method""" .. _example-series-item-170: .. dropdown:: item (test_series.py:245) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 235 :emphasize-lines: 11 return False def test_series_item(): """Test Series item method""" f_print_header("Test: Series item") try: # Single element Series s = pandasCore.Series([42.0]) val = s.item() assert val == 42.0, f"Expected 42.0, got {val}" # Multi-element Series should raise s_multi = pandasCore.Series([1.0, 2.0]) try: s_multi.item() f_print_error("item() should raise for multi-element Series") return False except RuntimeError: pass # Expected .. _example-series-memory_usage-171: .. dropdown:: memory_usage (test_series.py:204) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 194 :emphasize-lines: 11 return False def test_series_memory_usage(): """Test Series memory_usage method""" f_print_header("Test: Series memory_usage") try: s = pandasCore.Series([1.0, 2.0, 3.0]) mem = s.memory_usage() assert mem > 0, f"Expected positive memory usage, got {mem}" # Without index mem_no_idx = s.memory_usage(index=False) assert mem_no_idx > 0, f"Expected positive memory usage (no index), got {mem_no_idx}" assert mem >= mem_no_idx, "Memory with index should be >= without" f_print_success("Series memory_usage: passed") return True except Exception as e: .. _example-series-multiply-172: .. dropdown:: multiply (test_series_phase4.py:334) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 324 :emphasize-lines: 11 """Test arithmetic aliases (subtract, multiply, divide)""" f_print_header("Test: Series arithmetic aliases") try: s = pandasCore.Series([10.0, 20.0, 30.0]) # Test subtract result = s.subtract(5.0) assert result.to_list() == [5.0, 15.0, 25.0], "subtract failed" # Test multiply result = s.multiply(2.0) assert result.to_list() == [20.0, 40.0, 60.0], "multiply failed" # Test divide result = s.divide(2.0) assert result.to_list() == [5.0, 10.0, 15.0], "divide failed" f_print_success("arithmetic aliases: passed") return True except Exception as e: f_print_error(f"arithmetic aliases failed: {e}") .. _example-series-product-173: .. dropdown:: product (test_series_phase3.py:57) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 47 :emphasize-lines: 11 f_print_success(f"prod: {result} == 120.0") return True f_print_error(f"prod: {result} != 120.0") return False def test_product(): """Test Series.product() - alias for prod""" f_print_header("Test: product") s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) result = s.product() if result == 120.0: f_print_success(f"product: {result} == 120.0") return True f_print_error(f"product: {result} != 120.0") return False def test_mean(): """Test Series.mean()""" f_print_header("Test: mean") .. _example-series-ravel-174: .. dropdown:: ravel (test_series_phase5.py:233) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 223 :emphasize-lines: 11 def test_ravel(): """Test Series ravel method""" f_print_header("Test: Series ravel") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # ravel returns flattened array (list) result = s.ravel() assert result == [1.0, 2.0, 3.0], f"ravel failed: {result}" f_print_info(f" ravel(): {result}") f_print_success("Series ravel: passed") return True except Exception as e: f_print_error(f"Series ravel failed: {e}") return False .. _example-series-rdivmod-175: .. dropdown:: rdivmod (test_series_phase4.py:296) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 286 :emphasize-lines: 11 except Exception as e: f_print_error(f"divmod failed: {e}") return False def test_rdivmod(): """Test Series rdivmod""" f_print_header("Test: Series rdivmod") try: s = pandasCore.Series([3.0, 4.0, 5.0]) quot, rem = s.rdivmod(10.0) # divmod(10, [3, 4, 5]) expected_quot = [3.0, 2.0, 2.0] expected_rem = [1.0, 2.0, 0.0] assert quot.to_list() == expected_quot, f"Expected quot {expected_quot}, got {quot.to_list()}" assert rem.to_list() == expected_rem, f"Expected rem {expected_rem}, got {rem.to_list()}" f_print_success("rdivmod: passed") return True except Exception as e: f_print_error(f"rdivmod failed: {e}") return False .. _example-series-repeat-176: .. dropdown:: repeat (test_series_phase4.py:532) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 522 :emphasize-lines: 11 except Exception as e: f_print_error(f"explode failed: {e}") return False def test_repeat(): """Test Series repeat""" f_print_header("Test: Series repeat") try: s = pandasCore.Series([1.0, 2.0, 3.0]) result = s.repeat(2) expected = [1.0, 1.0, 2.0, 2.0, 3.0, 3.0] assert result.to_list() == expected, f"Expected {expected}, got {result.to_list()}" f_print_success("repeat: passed") return True except Exception as e: f_print_error(f"repeat failed: {e}") return False # ==================== I/O Tests ==================== .. _example-series-set_flags-177: .. dropdown:: set_flags (test_series.py:291) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 281 :emphasize-lines: 11 def test_series_set_flags(): """Test Series set_flags method""" f_print_header("Test: Series set_flags") try: s = pandasCore.Series([1.0, 2.0, 3.0]) # set_flags returns a copy (our simplified implementation) s_flagged = s.set_flags() assert s_flagged.to_list() == s.to_list(), "set_flags should return copy with same values" f_print_success("Series set_flags: passed") return True except Exception as e: f_print_error(f"Series set_flags failed: {e}") return False def test_series_to_frame(): .. _example-series-subtract-178: .. dropdown:: subtract (test_series_phase4.py:330) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 320 :emphasize-lines: 11 return False def test_aliases(): """Test arithmetic aliases (subtract, multiply, divide)""" f_print_header("Test: Series arithmetic aliases") try: s = pandasCore.Series([10.0, 20.0, 30.0]) # Test subtract result = s.subtract(5.0) assert result.to_list() == [5.0, 15.0, 25.0], "subtract failed" # Test multiply result = s.multiply(2.0) assert result.to_list() == [20.0, 40.0, 60.0], "multiply failed" # Test divide result = s.divide(2.0) assert result.to_list() == [5.0, 10.0, 15.0], "divide failed" .. _example-series-truncate-179: .. dropdown:: truncate (test_series_phase5.py:146) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 136 :emphasize-lines: 11 def test_truncate(): """Test Series truncate method""" f_print_header("Test: Series truncate") try: s = pandasCore.Series([1.0, 2.0, 3.0, 4.0, 5.0]) # Truncate with before truncated = s.truncate(before="1") f_print_info(f" truncate(before='1'): {truncated.to_list()}") # Truncate with after truncated = s.truncate(after="3") f_print_info(f" truncate(after='3'): {truncated.to_list()}") f_print_success("Series truncate: passed") return True except Exception as e: f_print_error(f"Series truncate failed: {e}") .. _example-series-values-180: .. dropdown:: values (test_accessor_descriptor.py:111) :class-title: example-dropdown .. code-block:: python :linenos: :lineno-start: 101 :emphasize-lines: 11 def test_string_series_str_accessor(): """Test that StringSeries.str accessor works on instance""" f_print_header("Test: StringSeries instance str accessor") try: # Create StringSeries data = ["HELLO", "world", "Test"] s = pandasCore.StringSeries(data, name="test_strings") f_print_success(f"Created StringSeries: {s.values()}") # Access .str on instance should return StringAccessor str_accessor = s.str type_name = type(str_accessor).__name__ f_print_info(f"type(s.str).__name__ = {type_name}") if type_name == "StringAccessor": f_print_success("s.str returns StringAccessor") else: f_print_error(f"Expected StringAccessor, got {type_name}")