L iddlmZddlZddlmZmZmZmZddlm Z m Z m Z m Z m Z mZmZmZddlmZmZddlmZmZmZmZmZmZmZmZmZmZmZm Z ddl!m"Z"m#Z#m$Z$ddl%m&Z&m'Z'dd l(m)Z)m*Z*dd l+m,Z,dd l-m.Z.dd l/m0Z0dd l1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>ddlm?Z?ddl@ZAddlBZCddlDZEddlFmGZGddlHmIZIddlJmKZKmLZLmMZMddlNmOZOmPZPddl%mQZQddl;mRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]Gdde e<Z^y)) annotationsN)IterableIteratorMappingSequence) TYPE_CHECKINGAnyCallableClassVarGenericLiteralcastoverload)ExprKindExprNode) ImplementationVersion_Implementation_validate_rolling_arguments ensure_type generate_repris_compliant_seriesis_eager_allowedis_index_selector no_defaultqualified_type_namesupports_arrow_c_stream)is_numpy_arrayis_numpy_array_1dis_numpy_scalar)_validate_dtype_validate_into_dtype) ComputeErrorInvalidOperationError)Expr)colSeriesCatNamespaceSeriesDateTimeNamespaceSeriesListNamespaceSeriesStringNamespaceSeriesStructNamespace) to_native) IntoSeriesT) ModuleType)NoReturn)Self)CompliantSeries) EagerAllowed IntoBackend NoDefault) DataFrameMultiIndexSelector)DType) ClosedIntervalFillNullStrategy IntoDTypeModeKeepStrategyNonNestedLiteralNumericLiteral PythonLiteral RankMethodRollingInterpolationMethodSingleIndexSelectorTemporalLiteral_1DArraycdeZdZUdZej Zded<eddZ eddZ ddZ ddZ e d dd Ze d dd ZeZd ed < dd ZdddZeddZeddZddZddZdddZddZddZeddZddZddZddZddZddZddZ eddZ!eddZ"dddddd d!d" dd#Z#dd$Z$dd%Z%dd&Z&dd'Z'dd(Z(dd)Z)dd*Z*dd+Z+dd,Z,dd-Z-dd.Z.dd/Z/dd0Z0dd1Z1dd2Z2d d3dd4Z3d d3dd5Z4 d dd6Z5dd7Z6dd8Z7dd9Z8dd:Z9dd;Z:dd<Z;d!d=dd>ZddBZ? ddd!ddC ddDZ@ddEZAddFZB deCddG ddHZDd!d!dIddJZEddKZFddLZG d ddMZHddNZI d ddOZJddPZKddQZLddRZMddSZNddTZOddUZPddVZQddWZRddXZSddYZTddZZUdd[ZVdd\ZWdd]ZXdd^ZYdd_ZZdd`Z[ddaZ\ddbZ]ddcZ^dddZ_ddeZ`ddfZaddgZbddhZcddiZdddjZeddkZfddlZgddmZhddnZiddoZjddpZkddqZlddrZmddsZnd!dtdduZod!d!dd!dv ddwZp ddxZqddyZrdddzZsddd{Ztddd|Zuddd}Zvdd~ZwddZxdd!d ddZydddZzddZ{eddddZ|eddZ|ddddZ|ddZ}d!d=ddZ~d!d=ddZd!d=ddZd!d=ddZdd!d ddZdd!d ddZdd!d d ddZdd!d d ddZddZddZdd!dtddZ dddd ddZejfddZddZddZddd!d ddZeddZeddZeddZeddZeddZy)Seriesa Narwhals Series, backed by a native series. Warning: This class is not meant to be instantiated directly - instead: - If the native object is a series from one of the supported backend (e.g. pandas.Series, polars.Series, pyarrow.ChunkedArray), you can use [`narwhals.from_native`][]: ```py narwhals.from_native(native_series, allow_series=True) narwhals.from_native(native_series, series_only=True) ``` - If the object is a generic sequence (e.g. a list or a tuple of values), you can create a series via [`narwhals.new_series`][], e.g.: ```py narwhals.new_series(name="price", values=[10.5, 9.4, 1.2], backend="pandas") ``` zClassVar[Version]_versionc|jSN)_compliant_seriesselfs U/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/narwhals/series.py _compliantzSeries._compliant`s%%%cddlm}|S)Nr)r:)narwhals.dataframer:)rPr:s rQ _dataframezSeries._dataframeds 0rSc`tttjd|jS)Nz_expr._from_series)series)r%rrSERIESrRrOs rQ_to_exprzSeries._to_exprjs$ X__&:4?? S  rSc||_t|r|j|_ydt |d}t |)NzQExpected Polars Series or an object which implements `__narwhals_series__`, got: .)_levelr__narwhals_series__rNtypeAssertionError)rPrXlevelmsgs rQ__init__zSeries.__init__osM?D v &**,  "ffjkqfresstuC % %rSNct|s d}t||r t|tj|}t |rt|j jj |j}|j|j|}|r||j|dS||dS|d|d}t|)uConstruct a Series from a NumPy ndarray. Arguments: name: Name of resulting Series. values: One-dimensional data represented as a NumPy ndarray. dtype: (Narwhals) dtype. If not provided, the native library may auto-infer it from `values`. backend: specifies which eager backend instantiate to. `backend` can be specified in various ways - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, `POLARS`, `MODIN` or `CUDF`. - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. Examples: >>> import numpy as np >>> import polars as pl >>> import narwhals as nw >>> >>> arr = np.arange(5, 10) >>> nw.Series.from_numpy("arr", arr, dtype=nw.Int8, backend="polars") ┌──────────────────┐ | Narwhals Series | |------------------| |shape: (5,) | |Series: 'arr' [i8]| |[ | | 5 | | 6 | | 7 | | 8 | | 9 | |] | └──────────────────┘ z)`from_numpy` only accepts 1D numpy arraysfullraz support in Narwhals is lazy-only, but `Series.from_numpy` is an eager-only function. Hint: you may want to use an eager backend and then call `.lazy`, e.g.: nw.Series.from_numpy(arr, backend='pyarrow').to_frame().lazy('')) r ValueErrorr"r from_backendrrK namespace compliant from_numpyaliasr clsnamevaluesdtypebackendrbimplementationnsrks rQrlzSeries.from_numpy{s\!(=CS/ !   ''44W= N +''44^DNNB f-33D9I9>>%0??y/ /QQ_P``b d orSct|r|j||||S|r t|t|tsdt |d}t |tj|}t|rX|jjj|j}|jj||||}||dS|d|d}t|) uConstruct a Series from an iterable. Arguments: name: Name of resulting Series. values: One-dimensional data represented as an iterable. dtype: (Narwhals) dtype. If not provided, the native library may auto-infer it from `values`. backend: specifies which eager backend instantiate to. `backend` can be specified in various ways - As `Implementation.` with `BACKEND` being `PANDAS`, `PYARROW`, `POLARS`, `MODIN` or `CUDF`. - As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`. - Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> values = [4, 1, 3, 2] >>> nw.Series.from_iterable("a", values, dtype=nw.UInt32, backend="pandas") ┌──────────────────────┐ | Narwhals Series | |----------------------| |0 4 | |1 1 | |2 3 | |3 2 | |Name: a, dtype: uint32| └──────────────────────┘ )rsz(Expected values to be an iterable, got: r\)contextrprrrerfz support in Narwhals is lazy-only, but `Series.from_iterable` is an eager-only function. Hint: you may want to use an eager backend and then call `.lazy`, e.g.: nw.Series.from_iterable('a', [1,2,3], backend='pyarrow').to_frame().lazy('rg)rrlr" isinstancerr TypeErrorrrirrKrjrk_series from_iterablerhrns rQr{zSeries.from_iterablesR & !>>$w>G G   '&(+<=PQW=X<[[\]CC. '44W= N +''44^DNNB 00U1Iy/ /]]k\lln p orSrrtcd}t|)Nathe truth value of a Series is ambiguous Here are some things you might want to try: - instead of `if s`, use `if not s.is_empty()` - instead of `s1 and s2`, use `s1 & s2` - instead of `s1 or s2`, use `s1 | s2` - instead of `s in [y, z]`, use `s.is_in([y, z])` )ry)rPrbs rQ__bool__zSeries.__bool__s B nrSc<|jj||S)N)rrcopy)rN __array__)rPrrrs rQrzSeries.__array__s%%//e$/GGrScyrMrPidxs rQ __getitem__zSeries.__getitem__>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> nw.from_native(s_native, series_only=True)[0] 1 >>> nw.from_native(s_native, series_only=True)[ ... :2 ... ].to_native() # doctest:+ELLIPSIS [ [ 1, 2 ] ] >iuz*Unexpected type for `Series.__getitem__`: z. Hints: - use `s.item` to select a single item. - Use `s[indices]` to select rows positionally. - Use `s.filter(mask)` to filter rows based on a boolean mask.)rxintr rrkindrNitemr1 __class___with_compliant _with_nativerr_ryrJ)rPrrbs rQrzSeries.__getitem__$s@ c3  C SYY^^z%A",S#"6#c(CC))..s3 3 c4>>+55 6&&t'='='J'J3'OPC %(>s?T?T(UV Vc3'''##D$:$:3$?@@rSc6|jjSrM)rN__native_namespace__rOs rQrzSeries.__native_namespace__[s%%::<=16.0.0' is required for `Series.__arrow_c_stream__` for object of type N)rr) chunked_array) rNnativer__arrow_c_stream__rPYARROW_backend_versionModuleNotFoundErrorr_narwhals._arrow.utilsrto_arrow)rPr native_series pa_versionexcrbrcas rQrzSeries.__arrow_c_stream__^s..55 "= 1 33EU3V V 4'//@@BJ  efjkxfyez{C%c* *7 4==? +$$6F$GG# 4efjkxfyez{C%c* 3 4sB C(CCc.|jjS)aConvert Narwhals series to native series. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2]) >>> s = nw.from_native(s_native, series_only=True) >>> s.to_native() # doctest: +NORMALIZE_WHITESPACE shape: (2,) Series: '' [i64] [ 1 2 ] )rNrrOs rQr1zSeries.to_nativeys"%%,,,rScv|j|jj||j|S)aSet value(s) at given position(s). Arguments: indices: Position(s) to set items at. values: Values to set. Note: This method always returns a new Series, without modifying the original one. Using this function in a for-loop is an anti-pattern, we recommend building up your positions and values beforehand and doing an update in one go. For example, instead of ```python for i in [1, 3, 2]: value = some_function(i) s = s.scatter(i, value) ``` prefer ```python positions = [1, 3, 2] values = [some_function(x) for x in positions] s = s.scatter(positions, values) ``` Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> df_native = pa.table({"a": [1, 2, 3], "b": [4, 5, 6]}) >>> df_nw = nw.from_native(df_native) >>> df_nw.with_columns(df_nw["a"].scatter([0, 1], [999, 888])).to_native() pyarrow.Table a: int64 b: int64 ---- a: [[999,888,3]] b: [[4,5,6]] )rrNscatter_extract_native)rPindicesrqs rQrzSeries.scatters9T##  " " * *7D4H4H4P Q  rSc8|jjfS)aGet the shape of the Series. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3]) >>> nw.from_native(s_native, series_only=True).shape (3,) )rNlenrOs rQshapez Series.shapes&&**,..rScBddlm}t||r |jS|S)Nr)rJ)narwhals.seriesrJrxrN)rPargrJs rQrzSeries._extract_natives * c6 "(( ( rSc<|j||jS)Nrf)rr])rPrXs rQrzSeries._with_compliants~~fDKK~88rSc||g|i|S)aPipe function call. Examples: >>> import polars as pl >>> import narwhals as nw >>> s_native = pl.Series([1, 2, 3]) >>> s = nw.from_native(s_native, series_only=True) >>> s.pipe(lambda x: x + 2).to_native() # doctest: +NORMALIZE_WHITESPACE shape: (3,) Series: '' [i64] [ 3 4 5 ] r)rPfunctionargskwargss rQpipez Series.pipes".t.v..rScRtd|jjS)NzNarwhals Series)rr1__repr__rOs rQrzSeries.__repr__s .0@0I0I0KLLrSc,t|jSrMrrNrOs rQ__len__zSeries.__len__s4))**rSc,t|jS)a\Return the number of elements in the Series. Null values count towards the total. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, None]]) >>> nw.from_native(s_native, series_only=True).len() 3 rrOs rQrz Series.lens4))**rSc.|jjS)aGet the data type of the Series. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3]) >>> nw.from_native(s_native, series_only=True).dtype Int64 )rNrrrOs rQrrz Series.dtypes%%+++rSc.|jjS)aGet the name of the Series. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series("foo", [1, 2, 3]) >>> nw.from_native(s_native, series_only=True).name 'foo' )rNrprOs rQrpz Series.names%%***rSTFcomspan half_lifealphaadjust min_samples ignore_nullsc d|j|jj|||||||S)a Compute exponentially-weighted moving average. Arguments: com: Specify decay in terms of center of mass, $\gamma$, with
$\alpha = \frac{1}{1+\gamma}\forall\gamma\geq0$ span: Specify decay in terms of span, $\theta$, with
$\alpha = \frac{2}{\theta + 1} \forall \theta \geq 1$ half_life: Specify decay in terms of half-life, $\tau$, with
$\alpha = 1 - \exp \left\{ \frac{ -\ln(2) }{ \tau } \right\} \forall \tau > 0$ alpha: Specify smoothing factor alpha directly, $0 < \alpha \leq 1$. adjust: Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings - When `adjust=True` (the default) the EW function is calculated using weights $w_i = (1 - \alpha)^i$ - When `adjust=False` the EW function is calculated recursively by $$ y_0=x_0 $$ $$ y_t = (1 - \alpha)y_{t - 1} + \alpha x_t $$ min_samples: Minimum number of observations in window required to have a value (otherwise result is null). ignore_nulls: Ignore missing values when calculating weights. - When `ignore_nulls=False` (default), weights are based on absolute positions. For example, the weights of $x_0$ and $x_2$ used in calculating the final weighted average of $[x_0, None, x_2]$ are $(1-\alpha)^2$ and $1$ if `adjust=True`, and $(1-\alpha)^2$ and $\alpha$ if `adjust=False`. - When `ignore_nulls=True`, weights are based on relative positions. For example, the weights of $x_0$ and $x_2$ used in calculating the final weighted average of $[x_0, None, x_2]$ are $1-\alpha$ and $1$ if `adjust=True`, and $1-\alpha$ and $\alpha$ if `adjust=False`. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series(name="a", data=[1, 2, 3]) >>> nw.from_native(s_native, series_only=True).ewm_mean( ... com=1, ignore_nulls=False ... ).to_native() 0 1.000000 1 1.666667 2 2.428571 Name: a, dtype: float64 r)rrNewm_mean)rPrrrrrrrs rQrzSeries.ewm_meansFt##  " " + +#') ,   rSclt||j|jj|S)a%Cast between data types. Arguments: dtype: Data type that the object will be cast into. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[True, False, True]]) >>> nw.from_native(s_native, series_only=True).cast(nw.Int64).to_native() [ [ 1, 0, 1 ] ] )r!rrNr)rPrrs rQrz Series.cast\s.* ##D$:$:$?$?$FGGrScl|j|jj|jS)uConvert to dataframe. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series("a", [1, 2]) >>> nw.from_native(s_native, series_only=True).to_frame().to_native() shape: (2, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 1 │ │ 2 │ └─────┘ rf)rVrNto_framer]rOs rQrzSeries.to_framets*&t55>>@ TTrSc6|jjS)a%Convert to list. Notes: This function converts to Python scalars. It's typically more efficient to keep your data in the format native to your original dataframe, so we recommend only calling this when you absolutely need to. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> nw.from_native(s_native, series_only=True).to_list() [1, 2, 3] )rNto_listrOs rQrzSeries.to_lists"%%--//rSc6|jjS)a*Reduce this Series to the mean value. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1.2, 4.2]) >>> nw.from_native(s_native, series_only=True).mean() np.float64(2.7) )rNmeanrOs rQrz Series.means%%**,,rSc6|jjS)aReduce this Series to the median value. Notes: Results might slightly differ across backends due to differences in the underlying algorithms used to compute the median. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[5, 3, 8]]) >>> nw.from_native(s_native, series_only=True).median() 5.0 )rNmedianrOs rQrz Series.medians%%,,..rSc6|jjS)aCalculate the sample skewness of the Series. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 1, 2, 10, 100]) >>> nw.from_native(s_native, series_only=True).skew() 1.4724267269058975 Notes: The skewness is a measure of the asymmetry of the probability distribution. A perfectly symmetric distribution has a skewness of 0. )rNskewrOs rQrz Series.skews%%**,,rSc6|jjS)a$Compute the kurtosis (Fisher's definition) without bias correction. Kurtosis is the fourth central moment divided by the square of the variance. The Fisher's definition is used where 3.0 is subtracted from the result to give 0.0 for a normal distribution. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 1, 2, 10, 100]) >>> nw.from_native(s_native, series_only=True).kurtosis() 0.2106571340718002 )rNkurtosisrOs rQrzSeries.kurtosiss%%..00rSc6|jjS)a:Returns the number of non-null elements in the Series. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, None]]) >>> nw.from_native(s_native, series_only=True).count() 2 )rNcountrOs rQrz Series.counts%%++--rSc6|jjS)aReturn whether any of the values in the Series are True. If there are no non-null elements, the result is `False`. Notes: Only works on Series of data type Boolean. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([False, True, False]) >>> nw.from_native(s_native, series_only=True).any() np.True_ )rNanyrOs rQrz Series.anys %%))++rSc6|jjS)aReturn whether all values in the Series are True. If there are no non-null elements, the result is `True`. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[False, True, False]]) >>> nw.from_native(s_native, series_only=True).all() False )rNallrOs rQrz Series.all%%))++rSc6|jjS)aGet the minimal value in this Series. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3]) >>> nw.from_native(s_native, series_only=True).min() 1 )rNminrOs rQrz Series.min%%))++rSc6|jjS)a$Get the maximum value in this Series. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3]) >>> nw.from_native(s_native, series_only=True).max() np.int64(3) )rNmaxrOs rQrz Series.maxrrSc6|jjS)a*Returns the index of the minimum value. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> nw.from_native(s_native, series_only=True).arg_min() 0 )rNarg_minrOs rQrzSeries.arg_min"%%--//rSc6|jjS)a Returns the index of the maximum value. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3]) >>> nw.from_native(s_native, series_only=True).arg_max() 2 )rNarg_maxrOs rQrzSeries.arg_max/rrSc6|jjS)acReduce this Series to the sum value. If there are no non-null elements, the result is zero. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> nw.from_native(s_native, series_only=True).sum() 6 )rNsumrOs rQrz Series.sum<rrSddofc:|jj|S)aGet the standard deviation of this Series. Arguments: ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, where N represents the number of elements. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3]) >>> nw.from_native(s_native, series_only=True).std() 1.0 r)rNstdrPrs rQrz Series.stdK%%))t)44rSc:|jj|S)aGet the variance of this Series. Arguments: ddof: "Delta Degrees of Freedom": the divisor used in the calculation is N - ddof, where N represents the number of elements. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> nw.from_native(s_native, series_only=True).var() 1.0 r)rNvarrs rQrz Series.var\rrSc|:|j|jj|j|S|:|j|jj |j|S|j|jj |j||j|S)aClip values in the Series. Arguments: lower_bound: Lower bound value. upper_bound: Upper bound value. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([-1, 1, -3, 3, -5, 5]) >>> nw.from_native(s_native, series_only=True).clip(-1, 3).to_native() 0 -1 1 1 2 -1 3 3 4 -1 5 3 dtype: int64 ) upper_bound) lower_bound)rr)rrN clip_upperr clip_lowerclip)rPrrs rQrz Series.clipms2  ''&&11 $ 4 4[ A2   ''&&11 $ 4 4[ A2  ##  " " ' ' 00= 00= (   rSc6|jjS)aGet the first element of the Series. Returns: A scalar value or `None` if the Series is empty. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3]) >>> s_nw = nw.from_native(s_native, series_only=True) >>> s_nw.first() 1 >>> s_nw.filter(s_nw > 5).first() is None True )rNfirstrOs rQrz Series.firsts"%%++--rSc6|jjS)aGet the last element of the Series. Returns: A scalar value or `None` if the Series is empty. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> s_nw = nw.from_native(s_native, series_only=True) >>> s_nw.last() 3 >>> s_nw.filter(s_nw > 5).last() is None True )rNlastrOs rQrz Series.lasts"%%**,,rScl|j|jjt|dS)aiCheck if the elements of this Series are in the other sequence. Arguments: other: Sequence of primitive type. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> s = nw.from_native(s_native, series_only=True) >>> s.is_in([3, 2, 8]).to_native() # doctest: +ELLIPSIS [ [ false, true, true ] ] T) pass_through)rrNis_inr1rPothers rQrz Series.is_ins2,##  " " ( (5t)L M  rScT|j|jjS)aFind elements where boolean Series is True. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, None, None, 2]) >>> nw.from_native( ... s_native, series_only=True ... ).is_null().arg_true().to_native() # doctest: +NORMALIZE_WHITESPACE shape: (2,) Series: '' [u32] [ 1 2 ] )rrNarg_truerOs rQrzSeries.arg_trues$$##D$:$:$C$C$EFFrScT|j|jjS)a-Drop null values. Notes: pandas handles null values differently from Polars and PyArrow. See [null_handling](../concepts/null_handling.md/) for reference. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([2, 4, None, 3, 5]) >>> nw.from_native(s_native, series_only=True).drop_nulls().to_native() 0 2.0 1 4.0 3 3.0 4 5.0 dtype: float64 )rrN drop_nullsrOs rQrzSeries.drop_nullss$&##D$:$:$E$E$GHHrScT|j|jjS)aCalculate the absolute value of each element. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[2, -4, 3]]) >>> nw.from_native( ... s_native, series_only=True ... ).abs().to_native() # doctest: +ELLIPSIS [ [ 2, 4, 3 ] ] )rrNabsrOs rQrz Series.abss$(##D$:$:$>$>$@AArSreversecX|j|jj|S)aCalculate the cumulative sum. Arguments: reverse: reverse the operation Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([2, 4, 3]) >>> nw.from_native(s_native, series_only=True).cum_sum().to_native() 0 2 1 6 2 9 dtype: int64 r)rrNcum_sumrPrs rQrzSeries.cum_sums)"##D$:$:$B$B7$B$STTrSmaintain_ordercX|j|jj|S)aReturns unique values of the series. Arguments: maintain_order: Keep the same order as the original series. This may be more expensive to compute. Settings this to `True` blocks the possibility to run on the streaming engine for Polars. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([2, 4, 4, 6]) >>> s = nw.from_native(s_native, series_only=True) >>> s.unique( ... maintain_order=True ... ).to_native() # doctest: +NORMALIZE_WHITESPACE shape: (3,) Series: '' [i64] [ 2 4 6 ] r)rrNunique)rPr s rQr z Series.unique+s.2##  " " ) ) ) H  rScT|j|jjS)aCalculate the difference with the previous element, for each element. Notes: pandas may change the dtype here, for example when introducing missing values in an integer column. To ensure, that the dtype doesn't change, you may want to use `fill_null` and `cast`. For example, to calculate the diff and fill missing values with `0` in a Int64 column, you could do: s.diff().fill_null(0).cast(nw.Int64) Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[2, 4, 3]]) >>> nw.from_native( ... s_native, series_only=True ... ).diff().to_native() # doctest: +ELLIPSIS [ [ null, 2, -1 ] ] )rrNdiffrOs rQr z Series.diffHs$:##D$:$:$?$?$ABBrSczt|td|j|jj |S)aShift values by `n` positions. Arguments: n: Number of indices to shift forward. If a negative value is passed, values are shifted in the opposite direction instead. Notes: pandas may change the dtype here, for example when introducing missing values in an integer column. To ensure, that the dtype doesn't change, you may want to use `fill_null` and `cast`. For example, to shift and fill missing values with `0` in a Int64 column, you could do: s.shift(1).fill_null(0).cast(nw.Int64) Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([2, 4, 3]) >>> nw.from_native(s_native, series_only=True).shift(1).to_native() 0 NaN 1 2.0 2 4.0 dtype: float64 n) param_name)rrrrNshiftrPrs rQrz Series.shiftgs26 Ass+##D$:$:$@$@$CDDrS)fractionwith_replacementseedc^|j|jj||||S)a}Sample randomly from this Series. Arguments: n: Number of items to return. Cannot be used with fraction. fraction: Fraction of items to return. Cannot be used with n. with_replacement: Allow values to be sampled more than once. seed: Seed for the random number generator. If set to None (default), a random seed is generated for each sample operation. Notes: The `sample` method returns a Series with a specified number of randomly selected items chosen from this Series. The results are not consistent across libraries. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3, 4]) >>> s = nw.from_native(s_native, series_only=True) >>> s.sample( ... fraction=1.0, with_replacement=True ... ).to_native() # doctest: +SKIP shape: (4,) Series: '' [i64] [ 1 4 3 4 ] )rrrr)rrNsample)rPrrrrs rQrz Series.samples<P##  " " ) )h9IPT *   rScX|j|jj|S)alRename the Series. Notes: This method is very cheap, but does not guarantee that data will be copied. For example: ```python s1: nw.Series s2 = s1.alias("foo") arr = s2.to_numpy() arr[0] = 999 ``` may (depending on the backend, and on the version) result in `s1`'s data being modified. We recommend: - if you need to alias an object and don't need the original one around any more, just use `alias` without worrying about it. - if you were expecting `alias` to copy data, then explicitly call `.clone` before calling `alias`. Arguments: name: The new name. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3], name="foo") >>> nw.from_native(s_native, series_only=True).alias("bar").to_native() 0 1 1 2 2 3 Name: bar, dtype: int64 rp)rrNrmrPrps rQrmz Series.aliass*H##D$:$:$@$@d$@$KLLrSc&|j|S)aRename the Series. Alias for `Series.alias()`. Notes: This method is very cheap, but does not guarantee that data will be copied. For example: ```python s1: nw.Series s2 = s1.rename("foo") arr = s2.to_numpy() arr[0] = 999 ``` may (depending on the backend, and on the version) result in `s1`'s data being modified. We recommend: - if you need to rename an object and don't need the original one around any more, just use `rename` without worrying about it. - if you were expecting `rename` to copy data, then explicitly call `.clone` before calling `rename`. Arguments: name: The new name. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series("foo", [1, 2, 3]) >>> s = nw.from_native(s_native, series_only=True) >>> s.rename("bar").to_native() # doctest: +NORMALIZE_WHITESPACE shape: (3,) Series: 'bar' [i64] [ 1 2 3 ] r)rmrs rQrenamez Series.renamesTzztz$$rS)default return_dtypec f|Ot|ts d}t|t|j }t|j }t|t sJt|t sJ|j|jj|||j||S)aNReplace all values by different values. Arguments: old: Sequence of values to replace. It also accepts a mapping of values to their replacement as syntactic sugar for `replace_strict(old=list(mapping.keys()), new=list(mapping.values()))`. new: Sequence of values to replace by. Length must match the length of `old`. default: Set values that were not replaced to this value. If no default is specified, (default), an error is raised if any values were not replaced. Accepts expression input. Non-expression inputs are parsed as literals. return_dtype: The data type of the resulting expression. If set to `None` (default), the data type is determined automatically based on the other inputs. Raises: InvalidOperationError: If any non-null values in the original column were not replaced, and no default was specified. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([3, 0, 1, 2], name="a") >>> nw.from_native(s_native, series_only=True).replace_strict( ... [0, 1, 2, 3], ["zero", "one", "two", "three"], return_dtype=nw.String ... ).to_native() 0 three 1 zero 2 one 3 two Name: a, dtype: object Replace values and set a default for values not in the mapping: >>> s_native = pd.Series([1, 2, 3, 4], name="a") >>> s_default = pd.Series(["beluga", "narwhal", "orca", "vaquita"]) >>> nw.from_native(s_native, series_only=True).replace_strict( ... {1: "one", 2: "two"}, ... default=nw.from_native(s_default, series_only=True), ... return_dtype=nw.String, ... ).to_native() 0 one 1 two 2 orca 3 vaquita Name: a, dtype: object zB`new` argument is required if `old` argument is not a Mapping type)oldnewrr) rxrrylistrqkeysrrrNreplace_strictr)rPr r!rrrbs rQr$zSeries.replace_strictsn ;c7+Zn$szz|$Csxxz"C#x(((#x(((##  " " 1 1,,W5) 2   rS descending nulls_lastcZ|j|jj||S)aSort this Series. Place null values first. Arguments: descending: Sort in descending order. nulls_last: Place null values last instead of first. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([5, None, 1, 2]) >>> s = nw.from_native(s_native, series_only=True) >>> s.sort(descending=True).to_native() # doctest: +NORMALIZE_WHITESPACE shape: (4,) Series: '' [i64] [ null 5 2 1 ] r%)rrNsort)rPr&r's rQr)z Series.sortQs0.##  " " ' ':* ' U  rScT|j|jjS)aReturns a boolean Series indicating which values are null. Notes: pandas handles null values differently from Polars and PyArrow. See [null_handling](../concepts/null_handling.md/) for reference. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, None]]) >>> nw.from_native( ... s_native, series_only=True ... ).is_null().to_native() # doctest:+ELLIPSIS [ [ false, false, true ] ] )rrNis_nullrOs rQr+zSeries.is_nullls$0##D$:$:$B$B$DEErScT|j|jjS)aQReturns a boolean Series indicating which values are NaN. Notes: pandas handles null values differently from Polars and PyArrow. See [null_handling](../concepts/null_handling.md/) for reference. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([0.0, None, 2.0], dtype="Float64") >>> nw.from_native(s_native, series_only=True).is_nan().to_native() 0 False 1 2 False dtype: boolean )rrNis_nanrOs rQr-z Series.is_nans$$##D$:$:$A$A$CDDrSc|| d}t||| d}t|||dvrd|}t||j|jj|j |||S)aFill null values using the specified value. Arguments: value: Value used to fill null values. strategy: Strategy used to fill null values. limit: Number of consecutive null values to fill when using the 'forward' or 'backward' strategy. Notes: - pandas handles null values differently from other libraries. See [null_handling](../concepts/null_handling.md/) for reference. - For pandas Series of `object` dtype, `fill_null` will not automatically change the Series' dtype as pandas used to do. Explicitly call `cast` if you want the dtype to change. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, None]) >>> >>> nw.from_native(s_native, series_only=True).fill_null(5).to_native() 0 1.0 1 2.0 2 5.0 dtype: float64 Or using a strategy: >>> nw.from_native(s_native, series_only=True).fill_null( ... strategy="forward", limit=1 ... ).to_native() 0 1.0 1 2.0 2 2.0 dtype: float64 z*cannot specify both `value` and `strategy`z0must specify either a fill `value` or `strategy`>forwardbackwardzstrategy not supported: )valuestrategylimit)rhrrN fill_nullr)rPr1r2r3rbs rQr4zSeries.fill_nullsT  !5>CS/ ! =X-DCS/ !  H4K$K,XJ7CS/ !##  " " , ,**51HE -   rScv|j|jj|j|S)a<Fill floating point NaN values with given value. Arguments: value: Value used to fill NaN values. Notes: This function only fills `'NaN'` values, not null ones, except for pandas which doesn't distinguish between them. See [null_handling](../concepts/null_handling.md/) for reference. Examples: >>> import polars as pl >>> import narwhals as nw >>> s_native = pl.Series([1.0, 2.0, float("nan"), None]) >>> result = nw.from_native(s_native, series_only=True).fill_nan(0) >>> result.to_native() # doctest: +NORMALIZE_WHITESPACE shape: (4,) Series: '' [f64] [ 1.0 2.0 0.0 null ] )r1)rrNfill_nanr)rPr1s rQr6zSeries.fill_nans94##  " " + +$2F2Fu2M + N  rSc|j|jj|j||j||S)aGet a boolean mask of the values that are between the given lower/upper bounds. Arguments: lower_bound: Lower bound value. upper_bound: Upper bound value. closed: Define which sides of the interval are closed (inclusive). Options are {"left", "right", "none", "both"}. Notes: If the value of the `lower_bound` is greater than that of the `upper_bound`, then the values will be False, as no value can satisfy the condition. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3, 4, 5]]) >>> s = nw.from_native(s_native, series_only=True) >>> s.is_between(2, 4, "right").to_native() # doctest: +ELLIPSIS [ [ false, false, true, true, false ] ] )closed)rrN is_betweenr)rPrrr8s rQr9zSeries.is_betweensPF##  " " - -$$[1$$[1 .   rSc6|jjS)aCount the number of unique values. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 2, 3]) >>> nw.from_native(s_native, series_only=True).n_unique() 3 )rNn_uniquerOs rQr;zSeries.n_uniques%%..00rSc<|jjddS)a'Convert to numpy. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3], name="a") >>> nw.from_native(s_native, series_only=True).to_numpy() array([1, 2, 3]...) N)r)rNto_numpyrOs rQr=zSeries.to_numpy)s %%..t$.??rSc6|jjS)afConvert to pandas Series. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series("a", [1, 2, 3]) >>> nw.from_native(s_native, series_only=True).to_pandas() 0 1 1 2 2 3 Name: a, dtype: int64 )rN to_pandasrOs rQr?zSeries.to_pandas6s%%//11rSc6|jjS)aConvert to polars Series. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3]]) >>> nw.from_native( ... s_native, series_only=True ... ).to_polars() # doctest: +NORMALIZE_WHITESPACE shape: (3,) Series: '' [i64] [ 1 2 3 ] )rN to_polarsrOs rQrAzSeries.to_polarsFs&%%//11rSct|j|jj|j|SrM)rrN__add__rrs rQrCzSeries.__add__[4##  " " * *4+?+?+F G  rSct|j|jj|j|SrM)rrN__radd__rrs rQrFzSeries.__radd__`4##  " " + +D,@,@,G H  rSct|j|jj|j|SrM)rrN__sub__rrs rQrIzSeries.__sub__erDrSct|j|jj|j|SrM)rrN__rsub__rrs rQrKzSeries.__rsub__jrGrSct|j|jj|j|SrM)rrN__mul__rrs rQrMzSeries.__mul__orDrSct|j|jj|j|SrM)rrN__rmul__rrs rQrOzSeries.__rmul__trGrSct|j|jj|j|SrM)rrN __truediv__rrs rQrQzSeries.__truediv__ys4##  " " . .t/C/CE/J K  rSct|j|jj|j|SrM)rrN __rtruediv__rrs rQrSzSeries.__rtruediv__~4##  " " / /0D0DU0K L  rSct|j|jj|j|SrM)rrN __floordiv__rrs rQrVzSeries.__floordiv__rTrSct|j|jj|j|SrM)rrN __rfloordiv__rrs rQrXzSeries.__rfloordiv__s4##  " " 0 01E1Ee1L M  rSct|j|jj|j|SrM)rrN__pow__rrs rQrZzSeries.__pow__rDrSct|j|jj|j|SrM)rrN__rpow__rrs rQr\zSeries.__rpow__rGrSct|j|jj|j|SrM)rrN__mod__rrs rQr^zSeries.__mod__rDrSct|j|jj|j|SrM)rrN__rmod__rrs rQr`zSeries.__rmod__rGrSct|j|jj|j|SrM)rrN__eq__rrs rQrbz Series.__eq__4##  " " ) )$*>*>u*E F  rSct|j|jj|j|SrM)rrN__ne__rrs rQrez Series.__ne__rcrSct|j|jj|j|SrM)rrN__gt__rrs rQrgz Series.__gt__rcrSct|j|jj|j|SrM)rrN__ge__rrs rQriz Series.__ge__rcrSct|j|jj|j|SrM)rrN__lt__rrs rQrkz Series.__lt__rcrSct|j|jj|j|SrM)rrN__le__rrs rQrmz Series.__le__rcrSct|j|jj|j|SrM)rrN__and__rrs rQrozSeries.__and__rDrSct|j|jj|j|SrM)rrN__rand__rrs rQrqzSeries.__rand__rGrSct|j|jj|j|SrM)rrN__or__rrs rQrsz Series.__or__rcrSct|j|jj|j|SrM)rrN__ror__rrs rQruzSeries.__ror__rDrScT|j|jjSrM)rrN __invert__rOs rQrwzSeries.__invert__s"##D$:$:$E$E$GHHrSct|j|jj|j|S)aFilter elements in the Series based on a condition. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([4, 10, 15, 34, 50]) >>> s_nw = nw.from_native(s_native, series_only=True) >>> s_nw.filter(s_nw > 10).to_native() 2 15 3 34 4 50 dtype: int64 )rrNfilterr)rP predicates rQryz Series.filters6##  " " ) )$*>*>y*I J  rScT|j|jjS)a@Get a mask of all duplicated rows in the Series. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3, 1]]) >>> nw.from_native( ... s_native, series_only=True ... ).is_duplicated().to_native() # doctest: +ELLIPSIS [ [ true, false, false, true ] ] )rrN is_duplicatedrOs rQr|zSeries.is_duplicateds$*##D$:$:$H$H$JKKrSc6|jjS)a{Check if the series is empty. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3]) >>> s_nw = nw.from_native(s_native, series_only=True) >>> s_nw.is_empty() False >>> s_nw.filter(s_nw > 10).is_empty() True )rNis_emptyrOs rQr~zSeries.is_emptys%%..00rScT|j|jjS)aGet a mask of all unique rows in the Series. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3, 1]) >>> nw.from_native(s_native, series_only=True).is_unique().to_native() 0 False 1 True 2 True 3 False dtype: bool )rrN is_uniquerOs rQrzSeries.is_uniques$##D$:$:$D$D$FGGrSc6|jjS)aCount the number of null values. Notes: pandas handles null values differently from Polars and PyArrow. See [null_handling](../concepts/null_handling.md/) for reference. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, None, None]]) >>> nw.from_native(s_native, series_only=True).null_count() 2 )rN null_countrOs rQrzSeries.null_count$s%%0022rScT|j|jjS)aYReturn a boolean mask indicating the first occurrence of each distinct value. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 1, 2, 3, 2]) >>> nw.from_native( ... s_native, series_only=True ... ).is_first_distinct().to_native() # doctest: +NORMALIZE_WHITESPACE shape: (5,) Series: '' [bool] [ true false true true false ] )rrNis_first_distinctrOs rQrzSeries.is_first_distinct5s$*##D$:$:$L$L$NOOrScT|j|jjS)aReturn a boolean mask indicating the last occurrence of each distinct value. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 1, 2, 3, 2]) >>> nw.from_native(s_native, series_only=True).is_last_distinct().to_native() 0 False 1 True 2 False 3 True 4 True dtype: bool )rrNis_last_distinctrOs rQrzSeries.is_last_distinctLs$ ##D$:$:$K$K$MNNrSr&c:|jj|S)aCheck if the Series is sorted. Arguments: descending: Check if the Series is sorted in descending order. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[3, 2, 1]]) >>> s_nw = nw.from_native(s_native, series_only=True) >>> s_nw.is_sorted(descending=False) False >>> s_nw.is_sorted(descending=True) True r)rN is_sorted)rPr&s rQrzSeries.is_sorted^s&%%//:/FFrSr)parallelrp normalizecv|j|jj|||||jS)a?Count the occurrences of unique values. Arguments: sort: Sort the output by count in descending order. If set to False (default), the order of the output is random. parallel: Execute the computation in parallel. Used for Polars only. name: Give the resulting count column a specific name; if `normalize` is True defaults to "proportion", otherwise defaults to "count". normalize: If true gives relative frequencies of the unique values - The original values as first column - Either count or proportion as second column, depending on normalize parameter. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 1, 2, 3, 2], name="s") >>> nw.from_native(s_native, series_only=True).value_counts( ... sort=True ... ).to_native() s count 0 1 2 1 2 2 2 3 1 rrf)rVrN value_countsr])rPr)rrprs rQrzSeries.value_countsssFD  " " / /H49 0 ++   rSc<|jj||S)aGet quantile value of the series. Note: pandas and Polars may have implementation differences for a given interpolation method. Arguments: quantile: Quantile between 0.0 and 1.0. interpolation: Interpolation method. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series(list(range(50))) >>> s_nw = nw.from_native(s_native, series_only=True) >>> [ ... s_nw.quantile(quantile=q, interpolation="nearest") ... for q in (0.1, 0.25, 0.5, 0.75, 0.9) ... ] [5.0, 12.0, 25.0, 37.0, 44.0] )quantile interpolation)rNr)rPrrs rQrzSeries.quantiles'0%%..]/  rSc|j|jj|j||j|S)aiTake values from self or other based on the given mask. Where mask evaluates true, take values from self. Where mask evaluates false, take values from other. Arguments: mask: Boolean Series other: Series of same type. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> data_native = pa.chunked_array([[1, 2, 3, 4, 5]]) >>> other_native = pa.chunked_array([[5, 4, 3, 2, 1]]) >>> mask_native = pa.chunked_array([[True, False, True, False, True]]) >>> >>> data_nw = nw.from_native(data_native, series_only=True) >>> other_nw = nw.from_native(other_native, series_only=True) >>> mask_nw = nw.from_native(mask_native, series_only=True) >>> >>> data_nw.zip_with(mask_nw, other_nw).to_native() # doctest: +ELLIPSIS [ [ 1, 4, 3, 2, 5 ] ] )rrNzip_withr)rPmaskrs rQrzSeries.zip_withsGB##  " " + +$$T*D,@,@,G   rSc|*|t|k\rd|dt|}t||jj|S)aReturn the Series as a scalar, or return the element at the given index. If no index is provided, this is equivalent to `s[0]`, with a check that the shape is (1,). With an index, this is equivalent to `s[index]`. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> nw.from_native(pl.Series("a", [1]), series_only=True).item() 1 >>> nw.from_native(pl.Series("a", [9, 8, 7]), series_only=True).item(-1) 7 zindex z# out of range for series of length )index)r IndexErrorrNr)rPrrbs rQrz Series.itemsP  #d)!35'!DSYKPCS/ !%%***77rScV|j|jj|S)aGet the first `n` rows. Arguments: n: Number of rows to return. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series(list(range(10))) >>> nw.from_native(s_native, series_only=True).head(3).to_native() 0 0 1 1 2 2 dtype: int64 )rrNheadrs rQrz Series.heads&"##D$:$:$?$?$BCCrScV|j|jj|S)a-Get the last `n` rows. Arguments: n: Number of rows to return. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([list(range(10))]) >>> s = nw.from_native(s_native, series_only=True) >>> s.tail(3).to_native() # doctest: +ELLIPSIS [ [ 7, 8, 9 ] ] )rrNtailrs rQrz Series.tails&,##D$:$:$?$?$BCCrScV|j|jj|S)aRound underlying floating point data by `decimals` digits. Arguments: decimals: Number of decimals to round by. Notes: For values exactly halfway between rounded decimal values pandas behaves differently than Polars and Arrow. pandas rounds to the nearest even value (e.g. -0.5 and 0.5 round to 0.0, 1.5 and 2.5 round to 2.0, 3.5 and 4.5 to 4.0, etc..). Polars and Arrow round away from 0 (e.g. -0.5 to -1.0, 0.5 to 1.0, 1.5 to 2.0, 2.5 to 3.0, etc..). Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1.12345, 2.56789, 3.901234]) >>> s = nw.from_native(s_native, series_only=True) >>> s.round(1).to_native() # doctest: +NORMALIZE_WHITESPACE shape: (3,) Series: '' [f64] [ 1.1 2.6 3.9 ] )rrNround)rPdecimalss rQrz Series.rounds&:##D$:$:$@$@$JKKrScT|j|jjS)aCompute the numerical floor. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> s_native = pa.chunked_array([[1.1, 4.3, -1.3]]) >>> s = nw.from_native(s_native, series_only=True) >>> s.floor().to_native() # doctest:+ELLIPSIS [ [ 1, 4, -2 ] ] )rrNfloorrOs rQrz Series.floor>s$$##D$:$:$@$@$BCCrScT|j|jjS)aCompute the numerical ceiling. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> s_native = pa.chunked_array([[1.1, 4.3, -1.3]]) >>> s = nw.from_native(s_native, series_only=True) >>> s.ceil().to_native() # doctest:+ELLIPSIS [ [ 2, 5, -1 ] ] )rrNceilrOs rQrz Series.ceilR$$##D$:$:$?$?$ABBrS_ separator drop_firstcr|j|jj|||jS)aGet dummy/indicator variables. Arguments: separator: Separator/delimiter used when generating column names. drop_first: Remove the first category from the variable being encoded. Notes: pandas and Polars handle null values differently. Polars distinguishes between NaN and Null, whereas pandas doesn't. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1, 2, 3], name="a") >>> s_nw = nw.from_native(s_native, series_only=True) >>> s_nw.to_dummies(drop_first=False).to_native() a_1 a_2 a_3 0 1 0 0 1 0 1 0 2 0 0 1 >>> s_nw.to_dummies(drop_first=True).to_native() a_2 a_3 0 0 0 1 1 0 2 0 1 rrf)rVrN to_dummiesr])rPrrs rQrzSeries.to_dummiesfs;@  " " - - j - Y++  rScZ|j|jj||S)aTake every nth value in the Series and return as new Series. Arguments: n: Gather every *n*-th row. offset: Starting index. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 2, 3, 4]]) >>> nw.from_native(s_native, series_only=True).gather_every( ... n=2, offset=1 ... ).to_native() # doctest:+ELLIPSIS [ [ 2, 4 ] ] )roffset)rrN gather_every)rPrrs rQrzSeries.gather_everys0.##  " " / /!F / C  rSc6|jjS)aConvert to arrow. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 2, 3, 4]) >>> nw.from_native( ... s_native, series_only=True ... ).to_arrow() # doctest:+NORMALIZE_WHITESPACE [ 1, 2, 3, 4 ] )rNrrOs rQrzSeries.to_arrows&%%..00rSrkeepcyrMrrPrs rQmodez Series.modes=@rScyrMrrs rQrz Series.modesADrScd}||vrd|d|d}t||j|jj|}|dk(r|j dS|S)aCompute the most occurring value(s). Can return multiple values. Note: For `keep="any"` a scalar is returned, while for `keep="all"` a Series in returned even in the case of unimodal values. Arguments: keep: Whether to keep all modes or any mode found. Remark that `keep='any'` is not deterministic for multimodal values. Examples: >>> import pandas as pd >>> import narwhals as nw >>> s_native = pd.Series([1, 1, 2, 2, 3]) >>> nw.from_native(s_native, series_only=True).mode().sort().to_native() 0 1 1 2 dtype: int64 )rrz`keep` must be one of z , found ''rrr)rhrrNrr)rPr_supported_keep_valuesrbresults rQrz Series.modesq,"0 - -*+A*B)D6QRSCS/ !%%d&<&<&A&At&A&LM!%v{{1~:F:rScT|j|jjS)a~Returns a boolean Series indicating which values are finite. Warning: Different backend handle null values differently. `is_finite` will return False for NaN and Null's in the Dask and pandas non-nullable backend, while for Polars, PyArrow and pandas nullable backends null values are kept as such. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[float("nan"), float("inf"), 2.0, None]]) >>> nw.from_native( ... s_native, series_only=True ... ).is_finite().to_native() # doctest: +ELLIPSIS [ [ false, false, true, null ] ] )rrN is_finiterOs rQrzSeries.is_finites$4##D$:$:$D$D$FGGrScX|j|jj|S)aqReturn the cumulative count of the non-null values in the series. Arguments: reverse: reverse the operation Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series(["x", "k", None, "d"]) >>> nw.from_native(s_native, series_only=True).cum_count( ... reverse=True ... ).to_native() # doctest:+NORMALIZE_WHITESPACE shape: (4,) Series: '' [u32] [ 3 2 1 1 ] r)rrN cum_countrs rQrzSeries.cum_counts).##D$:$:$D$DW$D$UVVrScX|j|jj|S)aReturn the cumulative min of the non-null values in the series. Arguments: reverse: reverse the operation Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([3, 1, None, 2]) >>> nw.from_native(s_native, series_only=True).cum_min().to_native() 0 3.0 1 1.0 2 NaN 3 1.0 dtype: float64 r)rrNcum_minrs rQrzSeries.cum_min s)$##D$:$:$B$B7$B$STTrScX|j|jj|S)aReturn the cumulative max of the non-null values in the series. Arguments: reverse: reverse the operation Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1, 3, None, 2]]) >>> nw.from_native( ... s_native, series_only=True ... ).cum_max().to_native() # doctest:+ELLIPSIS [ [ 1, 3, null, 3 ] ] r)rrNcum_maxrs rQrzSeries.cum_max( s)0##D$:$:$B$B7$B$STTrScX|j|jj|S)a_Return the cumulative product of the non-null values in the series. Arguments: reverse: reverse the operation Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1, 3, None, 2]) >>> nw.from_native( ... s_native, series_only=True ... ).cum_prod().to_native() # doctest:+NORMALIZE_WHITESPACE shape: (4,) Series: '' [i64] [ 1 3 null 6 ] r)rrNcum_prodrs rQrzSeries.cum_prodB s).##D$:$:$C$CG$C$TUUrS)rcenterct||\}}t|dk(r|S|j|jj |||S)aApply a rolling sum (moving sum) over the values. A window of length `window_size` will traverse the values. The resulting values will be aggregated to their sum. The window at a given row will include the row itself and the `window_size - 1` elements before it. Arguments: window_size: The length of the window in number of elements. It must be a strictly positive integer. min_samples: The number of values in the window that should be non-null before computing a result. If set to `None` (default), it will be set equal to `window_size`. If provided, it must be a strictly positive integer, and less than or equal to `window_size` center: Set the labels at the center of the window. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1.0, 2.0, 3.0, 4.0]) >>> nw.from_native(s_native, series_only=True).rolling_sum( ... window_size=2 ... ).to_native() 0 NaN 1 3.0 2 5.0 3 7.0 dtype: float64  window_sizerrrrr)rrrrN rolling_sum)rPrrrmin_samples_ints rQrzSeries.rolling_sum[ s_D(C#( $ _ t9>K##  " " . .'_V /   rSct||\}}t|dk(r|S|j|jj |||S)a]Apply a rolling mean (moving mean) over the values. A window of length `window_size` will traverse the values. The resulting values will be aggregated to their mean. The window at a given row will include the row itself and the `window_size - 1` elements before it. Arguments: window_size: The length of the window in number of elements. It must be a strictly positive integer. min_samples: The number of values in the window that should be non-null before computing a result. If set to `None` (default), it will be set equal to `window_size`. If provided, it must be a strictly positive integer, and less than or equal to `window_size` center: Set the labels at the center of the window. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[1.0, 2.0, 3.0, 4.0]]) >>> nw.from_native(s_native, series_only=True).rolling_mean( ... window_size=2 ... ).to_native() # doctest:+ELLIPSIS [ [ null, 1.5, 2.5, 3.5 ] ] rrr)rrrrN rolling_mean)rPrrrs rQrzSeries.rolling_mean s^L$?#$  [ t9>K##  " " / /'[ 0   rS)rrrct||\}}t|dk(r|S|j|jj ||||S)aApply a rolling variance (moving variance) over the values. A window of length `window_size` will traverse the values. The resulting values will be aggregated to their variance. The window at a given row will include the row itself and the `window_size - 1` elements before it. Arguments: window_size: The length of the window in number of elements. It must be a strictly positive integer. min_samples: The number of values in the window that should be non-null before computing a result. If set to `None` (default), it will be set equal to `window_size`. If provided, it must be a strictly positive integer, and less than or equal to `window_size`. center: Set the labels at the center of the window. ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. Examples: >>> import polars as pl >>> import narwhals as nw >>> >>> s_native = pl.Series([1.0, 3.0, 1.0, 4.0]) >>> nw.from_native(s_native, series_only=True).rolling_var( ... window_size=2, min_samples=1 ... ).to_native() # doctest:+NORMALIZE_WHITESPACE shape: (4,) Series: '' [f64] [ null 2.0 2.0 4.5 ] rrrrrr)rrrrN rolling_varrPrrrrs rQrzSeries.rolling_var saV$?#$  [ t9>K##  " " . .'[VZ /   rSct||\}}t|dk(r|S|j|jj ||||S)aApply a rolling standard deviation (moving standard deviation) over the values. A window of length `window_size` will traverse the values. The resulting values will be aggregated to their standard deviation. The window at a given row will include the row itself and the `window_size - 1` elements before it. Arguments: window_size: The length of the window in number of elements. It must be a strictly positive integer. min_samples: The number of values in the window that should be non-null before computing a result. If set to `None` (default), it will be set equal to `window_size`. If provided, it must be a strictly positive integer, and less than or equal to `window_size`. center: Set the labels at the center of the window. ddof: Delta Degrees of Freedom; the divisor for a length N window is N - ddof. Examples: >>> import pandas as pd >>> import narwhals as nw >>> >>> s_native = pd.Series([1.0, 3.0, 1.0, 4.0]) >>> nw.from_native(s_native, series_only=True).rolling_std( ... window_size=2, min_samples=1 ... ).to_native() 0 NaN 1 1.414214 2 1.414214 3 2.121320 dtype: float64 rrr)rrrrN rolling_stdrs rQrzSeries.rolling_std saP$?#$  [ t9>K##  " " . .'[VZ /   rSc#TK|jjEd{y7wrM)rN__iter__rOs rQrzSeries.__iter__* s))22444s (&(c8|jj|SrM)rN __contains__rs rQrzSeries.__contains__- s%%22599rSchd}||vrd|d}t||j|jj||S)aAssign ranks to data, dealing with ties appropriately. Notes: The resulting dtype may differ between backends. Arguments: method: The method used to assign ranks to tied elements. The following methods are available (default is 'average') - *"average"*: The average of the ranks that would have been assigned to all the tied values is assigned to each value. - *"min"*: The minimum of the ranks that would have been assigned to all the tied values is assigned to each value. (This is also referred to as "competition" ranking.) - *"max"*: The maximum of the ranks that would have been assigned to all the tied values is assigned to each value. - *"dense"*: Like "min", but the rank of the next highest element is assigned the rank immediately after those assigned to the tied elements. - *"ordinal"*: All values are given a distinct rank, corresponding to the order that the values occur in the Series. descending: Rank in descending order. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> s_native = pa.chunked_array([[3, 6, 1, 1, 6]]) >>> nw.from_native(s_native, series_only=True).rank( ... method="dense" ... ).to_native() # doctest:+ELLIPSIS [ [ 2, 3, 1, 1, 3 ] ] >rrdenseaverageordinalzTRanking method must be one of {'average', 'min', 'max', 'dense', 'ordinal'}. Found 'r)methodr&)rhrrNrank)rPrr&supported_rank_methodsrbs rQrz Series.rank0 scV"O / / $ S/ !##  " " ' 'v* ' M  rS bin_countinclude_breakpointc ZgtfdtdtDr d}t||d|d}t||jj |}n%d}||n|}|jj ||}|j||j S) uzBin values into buckets and count their occurrences. Warning: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. Arguments: bins: A monotonically increasing sequence of values. bin_count: If no bins provided, this will be used to determine the distance of the bins. include_breakpoint: Include a column that shows the intervals as categories. Examples: >>> import pandas as pd >>> import narwhals as nw >>> s_native = pd.Series([1, 3, 8, 8, 2, 1, 3], name="a") >>> nw.from_native(s_native, series_only=True).hist(bin_count=4) ┌────────────────────┐ | Narwhals DataFrame | |--------------------| | breakpoint count| |0 2.75 3| |1 4.50 2| |2 6.25 0| |3 8.00 2| └────────────────────┘ c3:K|]}|dz |k\yw)rNr).0rbinss rQ zSeries.hist.. s"Ga4A;$q')Gsrz bins must increase monotonicallyz>can only provide one of `bin_count` or `bins`, got: bin_count=z, bins=)rr rrf) rrangerr#rNhist_from_binshist_from_bin_countrVr])rPrrrrbrrs ` rQhistz Series.histg sB  G5CI3FGG8"3''$WYLX`[_Zab"3''++::.@;F G#,#4)I++??#8J@FvT[[99rScX|j|jj|S)uCompute the logarithm to a given base. Arguments: base: Given base, defaults to `e` Examples: >>> import pandas as pd >>> import narwhals as nw >>> s_native = pd.Series([1, 2, 4], name="a") >>> s = nw.from_native(s_native, series_only=True) >>> s.log(base=2) ┌───────────────────────┐ | Narwhals Series | |-----------------------| |0 0.0 | |1 1.0 | |2 2.0 | |Name: a, dtype: float64| └───────────────────────┘ )base)rrNlog)rPrs rQrz Series.log s)*##D$:$:$>$>D$>$IJJrScT|j|jjS)uCompute the exponent. Examples: >>> import pandas as pd >>> import narwhals as nw >>> s_native = pd.Series([-1, 0, 1], name="a") >>> s = nw.from_native(s_native, series_only=True) >>> s.exp() ┌───────────────────────┐ | Narwhals Series | |-----------------------| |0 0.367879 | |1 1.000000 | |2 2.718282 | |Name: a, dtype: float64| └───────────────────────┘ )rrNexprOs rQrz Series.exp s$$##D$:$:$>$>$@AArScT|j|jjS)uCompute the square root. Examples: >>> import pandas as pd >>> import narwhals as nw >>> s_native = pd.Series([1, 4, 9], name="a") >>> s = nw.from_native(s_native, series_only=True) >>> s.sqrt() ┌───────────────────────┐ | Narwhals Series | |-----------------------| |0 1.0 | |1 2.0 | |2 3.0 | |Name: a, dtype: float64| └───────────────────────┘ )rrNsqrtrOs rQrz Series.sqrt rrSgg& .>abs_tolrel_tol nans_equalc|jjsd|jd}t||j}|du}|rdn|}t |j ||||} |r|j |n|} | jj| j|} |r| j |n| } td| S)aGet a boolean mask of the values being close to the other values. Two values `a` and `b` are considered close if the following condition holds: $$ |a-b| \le max \{ \text{rel\_tol} \cdot max \{ |a|, |b| \}, \text{abs\_tol} \} $$ Arguments: other: Values to compare with. abs_tol: Absolute tolerance. This is the maximum allowed absolute difference between two values. Must be non-negative. rel_tol: Relative tolerance. This is the maximum allowed difference between two values, relative to the larger absolute value. Must be in the range [0, 1). nans_equal: Whether NaN values should be considered equal. Notes: The implementation of this method is symmetric and mirrors the behavior of `math.isclose`. Specifically note that this behavior is different to `numpy.isclose`. Examples: >>> import pyarrow as pa >>> import narwhals as nw >>> >>> data = [1.0, float("inf"), 1.41, None, float("nan")] >>> s_native = pa.chunked_array([data]) >>> s = nw.from_native(s_native, series_only=True) >>> s.is_close(1.4, abs_tol=0.1).to_native() # doctest:+ELLIPSIS [ [ false, false, true, null, false ] ] z.`is_close` operation not supported for dtype `z7` Hint: `is_close` is only supported for numeric typesN__nw_is_close__rr5) rr is_numericr$rpr&is_closerrselect get_columnr) rPrrrrrb orig_name name_is_nonetmp_nameexprrXrs rQrzSeries.is_close sbzz$$&@ MGG (, ,II  D( (4$)8}%% 7G & +7X&D"))$/::8D-9y)vFF##rSct|SrMr-rOs rQstrz Series.str $T**rSct|SrMr)rOs rQdtz Series.dt# s &t,,rSct|SrMr'rOs rQcatz Series.cat' s !$''rSct|SrMr+rOs rQr"z Series.list+ s "4((rSct|SrMr/rOs rQstructz Series.struct/ rrS)returnzCompliantSeries[IntoSeriesT])rztype[DataFrame[Any]])rr%)rXr raz&Literal['full', 'lazy', 'interchange']rNonerM) rprrqrHrrIntoDType | NonersIntoBackend[EagerAllowed]r Series[Any]) rprrqz Iterable[Any]rrr rsr rr )rr4)NN)rrr rz bool | NonerrH)rrFrr )rr;rr5)rz(SingleIndexSelector | MultiIndexSelectorr Any | Self)rr3)rz object | Nonerobject)rr2)rzint | Sequence[int]rqr rr5)rz tuple[int])rr rr )rXr rr5)rzCallable[[Any], Self]rr rr rr5)rr)rr)rr<)r float | Nonerrrrrrrboolrrrrrr5)rrr?rr5)rDataFrame[Any])rz list[Any])rfloat)rr)rr)rr )rrrr)r.Self | NumericLiteral | TemporalLiteral | Nonerrrr5)rrC)rr rr5)rr5)rrrr5)r rrr5)rrrr5) r int | Nonerrrrrrrr5)rprrr5) r z!Sequence[Any] | Mapping[Any, Any]r!zSequence[Any] | NonerzAny | NoDefaultrr rr5)r&rr'rrr5)NNN)r1Self | NonNestedLiteralr2zFillNullStrategy | Noner3rrr5)r1rrr5)both)rr rr r8r=rr5)rrH)rzpd.Series[Any])rz pl.Series)rrrr5)rzr rr5)r&rrr) r)rrrrpz str | Nonerrrr)rrrrErr)rr5rr5rr5)rrrr )r)r)rrrr5)rrrrrr)rrrrrr5)rz pa.Array[Any])rzLiteral['all']rr5)rzLiteral['any']rrA)rr@rr)rrrrrrrr5) rrrrrrrrrr5)rz Iterator[Any])rr rr)r)rrDr&rrr5)rzlist[float] | Nonerrrrrr)rrrr5) rzSelf | NumericLiteralrrrrrrrr5)rzSeriesStringNamespace[Self])rzSeriesDateTimeNamespace[Self])rzSeriesCatNamespace[Self])rzSeriesListNamespace[Self])rzSeriesStructNamespace[Self])__name__ __module__ __qualname____doc__rMAINrK__annotations__propertyrRrVrZrc classmethodrlr{rrtr}rrrrrr1rrrrrrrrrrrprrrrrrrrrrrrrrrrrrrrrrrrrrr r rrrmrrr$r)r+r-r4r6r9r;r=r?rArCrFrIrKrMrOrQrSrVrXrZr\r^r`rbrergrirkrmrorqrsrurwryr|r~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmatherrrrrrrr"rrrSrQrJrJIs(#*,,H. &&  & &%K &  & #' >>> > + > >>@ #' ;;; ; + ; ;;z'6&7NO7( H?? ??5An=H6-&, \ / /9/&M+ + , , + + !!"&""D D  D  D  D D D D  D LH0U*0& -/ -"1 .,$ , , , 0 0 ,"#5""#5&GKFJ* C* D*   * X.&-& 4G(I*B,*/U&05 :C>EB, "&!& , ,  ,  ,  ,  , \$ML*%^%)I $.)- I .I "I ! I ' I  I V*/5 6F4E,*.,0 7 &7 *7  7  7 r D"( ) )  )  )  ) V 1 @2 2*                        I (L.1"H"3"P.O$/4G0 ' '  '  '  '  ' R  .H  8% N8*D&D0L>D(C*#&%# # 37# # J 61*-2@@ DD/4;<H8,1W2*/U(*/U4+0V4>BRW- - 0:- KO- - `>BRW1 1 0:1 KO1 1 n#' 6 6  6  6  6  6 x#' 3 3  3  3  3  3 j5:5 5 r$(3:!%#' 3: 3: 3: ! 3:  3:j!%K.B(C0 B$$B$ B$  B$  B$ B$H++--(())++rSrJ)_ __future__rrcollections.abcrrrrtypingrr r r r r rrnarwhals._expression_parsingrrnarwhals._utilsrrrrrrrrrrrrnarwhals.dependenciesrrr narwhals.dtypesr!r"narwhals.exceptionsr#r$ narwhals.exprr%narwhals.functionsr&narwhals.series_catr(narwhals.series_dtr*narwhals.series_listr,narwhals.series_strr.narwhals.series_structr0narwhals.translater1narwhals.typingr2typesr3r4pandaspdpolarsplpyarrowpatyping_extensionsr5narwhals._compliantr6narwhals._typingr7r8r9rUr:r;r<r=r>r?r@rArBrCrDrErFrGrHrJrrSrQr<s" AA   <    UTAC"26458(' &3EE@%     h++W[ !h++rS