polars.Series¶
- class polars.Series(name: Optional[Union[str, Sequence[Any], polars.internals.series.Series, pyarrow.lib.Array, numpy.ndarray, pandas.core.series.Series, pandas.core.indexes.datetimes.DatetimeIndex]] = None, values: Optional[Union[Sequence[Any], polars.internals.series.Series, pyarrow.lib.Array, numpy.ndarray, pandas.core.series.Series, pandas.core.indexes.datetimes.DatetimeIndex]] = None, dtype: Optional[Type[polars.datatypes.DataType]] = None, strict: bool = True, nan_to_null: bool = False)¶
A Series represents a single column in a polars DataFrame.
- Parameters
- namestr, default None
Name of the series. Will be used as a column name when used in a DataFrame. When not specified, name is set to an empty string.
- valuesArrayLike, default None
One-dimensional data in various forms. Supported are: Sequence, Series, pyarrow Array, and numpy ndarray.
- dtypeDataType, default None
Polars dtype of the Series data. If not specified, the dtype is inferred.
- strict
Throw error on numeric overflow
- nan_to_null
In case a numpy arrow is used to create this Series, indicate how to deal with np.nan
Examples
Constructing a Series by specifying name and values positionally:
>>> s = pl.Series("a", [1, 2, 3]) >>> s shape: (3,) Series: 'a' [i64] [ 1 2 3 ]
Notice that the dtype is automatically inferred as a polars Int64:
>>> s.dtype <class 'polars.datatypes.Int64'>
Constructing a Series with a specific dtype:
>>> s2 = pl.Series("a", [1, 2, 3], dtype=pl.Float32) >>> s2 shape: (3,) Series: 'a' [f32] [ 1 2 3 ]
It is possible to construct a Series with values as the first positional argument. This syntax considered an anti-pattern, but it can be useful in certain scenarios. You must specify any other arguments through keywords.
>>> s3 = pl.Series([1, 2, 3]) >>> s3 shape: (3,) Series: '' [i64] [ 1 2 3 ]
- Attributes
arr
Create an object namespace of all list related methods.
cat
Create an object namespace of all categorical related methods.
dt
Create an object namespace of all datetime related methods.
dtype
Get the data type of this Series.
inner_dtype
Get the inner dtype in of a List typed Series
name
Get the name of this Series.
shape
Shape of this Series.
str
Create an object namespace of all string related methods.
struct
Create an object namespace of all struct related methods.
time_unit
Get the time unit of underlying Datetime Series as {“ns”, “us”, “ms”}
Methods
abs
()Take absolute values
alias
(name)Rename the Series
all
()Check if all boolean values in the column are True
any
()Check if any boolean value in the column is True
append
(other[, append_chunks])Append a Series to this one.
apply
(func[, return_dtype])Apply a function over elements in this Series and return a new Series.
arccos
()Compute the element-wise value for Trigonometric Inverse cosine.
arcsin
()Compute the element-wise value for Trigonometric Inverse sine.
arctan
()Compute the element-wise value for Trigonometric Inverse tangent.
arg_max
()Get the index of the maximal value.
arg_min
()Get the index of the minimal value.
arg_true
()Get index values where Boolean Series evaluate True.
Get unique index as Series.
argsort
([reverse, nulls_last])Index location of the sorted variant of this Series.
cast
(dtype[, strict])Cast between data types.
ceil
()Ceil underlying floating point array to the highest integers smaller or equal to the float value.
Get the length of each individual chunk.
clip
(min_val, max_val)Clip (limit) the values in an array to any value that fits in 64 floating poitns range.
clone
()Cheap deep clones.
cos
()Compute the element-wise value for Trigonometric cosine.
cummax
([reverse])Get an array with the cumulative max computed at every element.
cummin
([reverse])Get an array with the cumulative min computed at every element.
cumprod
([reverse])Get an array with the cumulative product computed at every element.
cumsum
([reverse])Get an array with the cumulative sum computed at every element.
cumulative_eval
(expr[, min_periods, parallel])Run an expression over a sliding window that increases 1 slot every iteration.
describe
()Quick summary statistics of a series.
diff
([n, null_behavior])Calculate the n-th discrete difference.
dot
(other)Compute the dot/inner product between two Series
Create a new Series that copies data from this Series without null values.
entropy
([base, normalize])Compute the entropy as -sum(pk * log(pk).
Returns an estimation of the total (heap) allocated size of the Series in bytes.
ewm_mean
([com, span, half_life, alpha, ...])Exponential moving average.
ewm_std
([com, span, half_life, alpha, ...])Exponential moving standard deviation.
ewm_var
([com, span, half_life, alpha, ...])Exponential moving standard variation.
exp
()Return the exponential element-wise
explode
()Explode a list or utf8 Series.
extend_constant
(value, n)Extend the Series with given number of values.
fill_nan
(fill_value)Fill floating point NaN value with a fill value
fill_null
(strategy)Fill null values using a filling strategy, literal, or Expr.
filter
(predicate)Filter elements by a boolean mask.
floor
()Floor underlying floating point array to the lowest integers smaller or equal to the float value.
Returns True if the Series has a validity bitmask.
hash
([k0, k1, k2, k3])Hash the Series.
head
([length])Get first N elements as Series.
Interpolate intermediate values.
Check if this Series is a Boolean.
Check if this Series datatype is datelike.
Get mask of all duplicated values.
Get mask of finite values if Series dtype is Float.
is_first
()Get a mask of the first unique value.
is_float
()Check if this Series has floating point numbers.
is_in
(other)Check if elements of this Series are in the right Series, or List values of the right Series.
Get mask of infinite values if Series dtype is Float.
is_nan
()Get mask of NaN values if Series dtype is Float.
Get negated mask of NaN values if Series dtype is_not Float.
Get mask of non null values.
is_null
()Get mask of null values.
Check if this Series datatype is numeric.
Get mask of all unique values.
is_utf8
()Checks if this Series datatype is a Utf8.
kurtosis
([fisher, bias])Compute the kurtosis (Fisher or Pearson) of a dataset.
len
()Length of this Series.
limit
([num_elements])Take n elements from this Series.
log
([base])Compute the logarithm to a given base
log10
()Return the base 10 logarithm of the input array, element-wise.
max
()Get the maximum value in this Series.
mean
()Reduce this Series to the mean value.
median
()Get the median of this Series.
min
()Get the minimal value in this Series.
mode
()Compute the most occurring value(s).
n_chunks
()Get the number of chunks that this Series contains.
n_unique
()Count the number of unique values in this Series.
Count the null values in this Series.
pct_change
([n])Percentage change (as fraction) between current element and most-recent non-null element at least n period(s) before the current element.
peak_max
()Get a boolean mask of the local maximum peaks.
peak_min
()Get a boolean mask of the local minimum peaks.
product
()Reduce this Series to the product value.
quantile
(quantile[, interpolation])Get the quantile value of this Series.
rank
([method, reverse])Assign ranks to data, dealing with ties appropriately.
rechunk
()Create a single chunk of memory for this Series.
reinterpret
([signed])Reinterpret the underlying bits as a signed/unsigned integer.
rename
()Rename this Series.
reshape
(dims)Reshape this Series to a flat series, shape: (len,) or a List series, shape: (rows, cols)
rolling_apply
(function, window_size[, ...])Allows a custom rolling window function.
rolling_max
(window_size[, weights, ...])Apply a rolling max (moving max) over the values in this array.
rolling_mean
(window_size[, weights, ...])Apply a rolling mean (moving mean) over the values in this array.
rolling_median
(window_size[, weights, ...])Compute a rolling median
rolling_min
(window_size[, weights, ...])apply a rolling min (moving min) over the values in this array.
rolling_quantile
(quantile[, interpolation, ...])Compute a rolling quantile
rolling_skew
(window_size[, bias])Compute a rolling skew
rolling_std
(window_size[, weights, ...])Compute a rolling std dev
rolling_sum
(window_size[, weights, ...])Apply a rolling sum (moving sum) over the values in this array.
rolling_var
(window_size[, weights, ...])Compute a rolling variance.
round
(decimals)Round underlying floating point data by decimals digits.
sample
([n, frac, with_replacement, shuffle, ...])Sample from this Series by setting either n or frac.
series_equal
(other[, null_equal, strict])Check if series is equal with another Series.
set
(filter, value)Set masked values.
set_at_idx
(idx, value)Set values at the index locations.
shift
([periods])Shift the values by a given period and fill the parts that will be empty due to this operation with Nones.
shift_and_fill
(periods, fill_value)Shift the values by a given period and fill the parts that will be empty due to this operation with the result of the fill_value expression.
Shrink memory usage of this Series to fit the exact capacity needed to hold the data.
shuffle
([seed])Shuffle the contents of this Series.
sign
()Returns an element-wise indication of the sign of a number.
sin
()Compute the element-wise value for Trigonometric sine.
skew
([bias])Compute the sample skewness of a data set.
slice
(offset, length)Get a slice of this Series.
sort
()Sort this Series.
sqrt
()Compute the square root of the elements
std
([ddof])Get the standard deviation of this Series.
sum
()Reduce this Series to the sum value.
tail
([length])Get last N elements as Series.
take
(indices)Take values by index.
take_every
(n)Take every nth value in the Series and return as new Series.
tan
()Compute the element-wise value for Trigonometric tangent.
to_arrow
()Get the underlying Arrow Array.
Get dummy variables.
to_frame
()Cast this Series to a DataFrame.
to_list
([use_pyarrow])Convert this Series to a Python List.
to_numpy
(*args[, zero_copy_only])Convert this Series to numpy.
Convert this Series to a pandas Series
Cast to physical representation of the logical dtype.
unique
([maintain_order])Get unique elements in series.
Returns a count of the unique values in the order of appearance.
Count the unique values in a Series.
var
([ddof])Get variance of this Series.
view
([ignore_nulls])Get a view into this Series data with a numpy array.
zip_with
(mask, other)Where mask evaluates true, take values from self.
drop_nans
inner
- __init__(name: Optional[Union[str, Sequence[Any], polars.internals.series.Series, pyarrow.lib.Array, numpy.ndarray, pandas.core.series.Series, pandas.core.indexes.datetimes.DatetimeIndex]] = None, values: Optional[Union[Sequence[Any], polars.internals.series.Series, pyarrow.lib.Array, numpy.ndarray, pandas.core.series.Series, pandas.core.indexes.datetimes.DatetimeIndex]] = None, dtype: Optional[Type[polars.datatypes.DataType]] = None, strict: bool = True, nan_to_null: bool = False)¶
Methods
__init__
([name, values, dtype, strict, ...])abs
()Take absolute values
alias
(name)Rename the Series
all
()Check if all boolean values in the column are True
any
()Check if any boolean value in the column is True
append
(other[, append_chunks])Append a Series to this one.
apply
(func[, return_dtype])Apply a function over elements in this Series and return a new Series.
arccos
()Compute the element-wise value for Trigonometric Inverse cosine.
arcsin
()Compute the element-wise value for Trigonometric Inverse sine.
arctan
()Compute the element-wise value for Trigonometric Inverse tangent.
arg_max
()Get the index of the maximal value.
arg_min
()Get the index of the minimal value.
arg_true
()Get index values where Boolean Series evaluate True.
Get unique index as Series.
argsort
([reverse, nulls_last])Index location of the sorted variant of this Series.
cast
(dtype[, strict])Cast between data types.
ceil
()Ceil underlying floating point array to the highest integers smaller or equal to the float value.
Get the length of each individual chunk.
clip
(min_val, max_val)Clip (limit) the values in an array to any value that fits in 64 floating poitns range.
clone
()Cheap deep clones.
cos
()Compute the element-wise value for Trigonometric cosine.
cummax
([reverse])Get an array with the cumulative max computed at every element.
cummin
([reverse])Get an array with the cumulative min computed at every element.
cumprod
([reverse])Get an array with the cumulative product computed at every element.
cumsum
([reverse])Get an array with the cumulative sum computed at every element.
cumulative_eval
(expr[, min_periods, parallel])Run an expression over a sliding window that increases 1 slot every iteration.
describe
()Quick summary statistics of a series.
diff
([n, null_behavior])Calculate the n-th discrete difference.
dot
(other)Compute the dot/inner product between two Series
Create a new Series that copies data from this Series without null values.
entropy
([base, normalize])Compute the entropy as -sum(pk * log(pk).
Returns an estimation of the total (heap) allocated size of the Series in bytes.
ewm_mean
([com, span, half_life, alpha, ...])Exponential moving average.
ewm_std
([com, span, half_life, alpha, ...])Exponential moving standard deviation.
ewm_var
([com, span, half_life, alpha, ...])Exponential moving standard variation.
exp
()Return the exponential element-wise
explode
()Explode a list or utf8 Series.
extend_constant
(value, n)Extend the Series with given number of values.
fill_nan
(fill_value)Fill floating point NaN value with a fill value
fill_null
(strategy)Fill null values using a filling strategy, literal, or Expr.
filter
(predicate)Filter elements by a boolean mask.
floor
()Floor underlying floating point array to the lowest integers smaller or equal to the float value.
Returns True if the Series has a validity bitmask.
hash
([k0, k1, k2, k3])Hash the Series.
head
([length])Get first N elements as Series.
inner
()Interpolate intermediate values.
Check if this Series is a Boolean.
Check if this Series datatype is datelike.
Get mask of all duplicated values.
Get mask of finite values if Series dtype is Float.
is_first
()Get a mask of the first unique value.
is_float
()Check if this Series has floating point numbers.
is_in
(other)Check if elements of this Series are in the right Series, or List values of the right Series.
Get mask of infinite values if Series dtype is Float.
is_nan
()Get mask of NaN values if Series dtype is Float.
Get negated mask of NaN values if Series dtype is_not Float.
Get mask of non null values.
is_null
()Get mask of null values.
Check if this Series datatype is numeric.
Get mask of all unique values.
is_utf8
()Checks if this Series datatype is a Utf8.
kurtosis
([fisher, bias])Compute the kurtosis (Fisher or Pearson) of a dataset.
len
()Length of this Series.
limit
([num_elements])Take n elements from this Series.
log
([base])Compute the logarithm to a given base
log10
()Return the base 10 logarithm of the input array, element-wise.
max
()Get the maximum value in this Series.
mean
()Reduce this Series to the mean value.
median
()Get the median of this Series.
min
()Get the minimal value in this Series.
mode
()Compute the most occurring value(s).
n_chunks
()Get the number of chunks that this Series contains.
n_unique
()Count the number of unique values in this Series.
Count the null values in this Series.
pct_change
([n])Percentage change (as fraction) between current element and most-recent non-null element at least n period(s) before the current element.
peak_max
()Get a boolean mask of the local maximum peaks.
peak_min
()Get a boolean mask of the local minimum peaks.
product
()Reduce this Series to the product value.
quantile
(quantile[, interpolation])Get the quantile value of this Series.
rank
([method, reverse])Assign ranks to data, dealing with ties appropriately.
rechunk
()Create a single chunk of memory for this Series.
reinterpret
([signed])Reinterpret the underlying bits as a signed/unsigned integer.
rename
()Rename this Series.
reshape
(dims)Reshape this Series to a flat series, shape: (len,) or a List series, shape: (rows, cols)
rolling_apply
(function, window_size[, ...])Allows a custom rolling window function.
rolling_max
(window_size[, weights, ...])Apply a rolling max (moving max) over the values in this array.
rolling_mean
(window_size[, weights, ...])Apply a rolling mean (moving mean) over the values in this array.
rolling_median
(window_size[, weights, ...])Compute a rolling median
rolling_min
(window_size[, weights, ...])apply a rolling min (moving min) over the values in this array.
rolling_quantile
(quantile[, interpolation, ...])Compute a rolling quantile
rolling_skew
(window_size[, bias])Compute a rolling skew
rolling_std
(window_size[, weights, ...])Compute a rolling std dev
rolling_sum
(window_size[, weights, ...])Apply a rolling sum (moving sum) over the values in this array.
rolling_var
(window_size[, weights, ...])Compute a rolling variance.
round
(decimals)Round underlying floating point data by decimals digits.
sample
([n, frac, with_replacement, shuffle, ...])Sample from this Series by setting either n or frac.
series_equal
(other[, null_equal, strict])Check if series is equal with another Series.
set
(filter, value)Set masked values.
set_at_idx
(idx, value)Set values at the index locations.
shift
([periods])Shift the values by a given period and fill the parts that will be empty due to this operation with Nones.
shift_and_fill
(periods, fill_value)Shift the values by a given period and fill the parts that will be empty due to this operation with the result of the fill_value expression.
Shrink memory usage of this Series to fit the exact capacity needed to hold the data.
shuffle
([seed])Shuffle the contents of this Series.
sign
()Returns an element-wise indication of the sign of a number.
sin
()Compute the element-wise value for Trigonometric sine.
skew
([bias])Compute the sample skewness of a data set.
slice
(offset, length)Get a slice of this Series.
sort
()Sort this Series.
sqrt
()Compute the square root of the elements
std
([ddof])Get the standard deviation of this Series.
sum
()Reduce this Series to the sum value.
tail
([length])Get last N elements as Series.
take
(indices)Take values by index.
take_every
(n)Take every nth value in the Series and return as new Series.
tan
()Compute the element-wise value for Trigonometric tangent.
to_arrow
()Get the underlying Arrow Array.
Get dummy variables.
to_frame
()Cast this Series to a DataFrame.
to_list
([use_pyarrow])Convert this Series to a Python List.
to_numpy
(*args[, zero_copy_only])Convert this Series to numpy.
Convert this Series to a pandas Series
Cast to physical representation of the logical dtype.
unique
([maintain_order])Get unique elements in series.
Returns a count of the unique values in the order of appearance.
Count the unique values in a Series.
var
([ddof])Get variance of this Series.
view
([ignore_nulls])Get a view into this Series data with a numpy array.
zip_with
(mask, other)Where mask evaluates true, take values from self.
Attributes
Create an object namespace of all list related methods.
Create an object namespace of all categorical related methods.
Create an object namespace of all datetime related methods.
Get the data type of this Series.
Get the inner dtype in of a List typed Series
Get the name of this Series.
Shape of this Series.
Create an object namespace of all string related methods.
struct
Create an object namespace of all struct related methods.
Get the time unit of underlying Datetime Series as {"ns", "us", "ms"}