Series#

The Series class represents a one-dimensional labeled array capable of holding any data type. It is the building block of a DataFrame - each column in a DataFrame is a Series.

Constructor#

Create a new Series from a PHP array.

param string $name:

Name of the Series

param array $values:

Array of values (integers, floats, strings, booleans, or nulls)

raises Polars\Exception:

If values cannot be converted to Series

Example:

$integers = new Series('numbers', [1, 2, 3, 4, 5]);
$floats = new Series('decimals', [1.5, 2.5, 3.5]);
$strings = new Series('names', ['Alice', 'Bob', 'Charlie']);
$booleans = new Series('flags', [true, false, true]);
$empty = new Series('empty', []);

Properties#

getName#

Get the name of the Series.

returns:

string - Series name

getDtype#

Get the data type of the Series.

returns:

DataType - The data type

getShape#

Get the shape of the Series as [length].

returns:

int[] - Array with single element [length]

getFlags#

Get flags that are set on the Series.

returns:

array<string, bool> - Associative array with flag names as keys and boolean values

The returned flags depend on the Series data type:

  • SORTED_ASC — true if the Series is known to be sorted in ascending order. Present on all Series.

  • SORTED_DESC — true if the Series is known to be sorted in descending order. Present on all Series.

  • FAST_EXPLODE — true if the list values can be exploded without additional validity checks. Only present on List-type Series (e.g. after calling implode()).

Example:

$s = new Series('x', [1, 2, 3, 4, 5]);
$s->getName();   // 'x'
$s->getShape();  // [5]

$s->getFlags(); // ['SORTED_ASC' => false, 'SORTED_DESC' => false]

$sorted = $s->sort();
$sorted->getFlags(); // ['SORTED_ASC' => true, 'SORTED_DESC' => false]

$list = $s->implode();
$list->getFlags(); // ['SORTED_ASC' => false, 'SORTED_DESC' => false, 'FAST_EXPLODE' => true]

Dimensions#

len#

Get the number of elements in the Series.

returns:

int - Number of elements

isEmpty#

Check if Series is empty.

returns:

bool

count#

Get the number of elements (Countable interface).

returns:

int

Example:

$s = new Series('x', [1, 2, 3]);
$s->len();      // 3
$s->isEmpty();  // false
count($s);      // 3

Array Access#

Series implements ArrayAccess, allowing bracket notation for accessing elements.

offsetGet#

Get value at index. Supports negative indexing.

param int $offset:

Index (supports negative values for indexing from end)

returns:

mixed - Value at index

raises Polars\Exception:

If index is out of bounds

offsetExists#

Check if an index exists.

param int $offset:

Index to check

returns:

bool

offsetSet / offsetUnset#

Not supported. Series are immutable.

Example:

$s = new Series('x', [10, 20, 30, 40, 50]);
$s[0];   // 10
$s[2];   // 30
$s[-1];  // 50 (last element)
$s[-2];  // 40 (second to last)

isset($s[0]);  // true
isset($s[10]); // false

Element Access#

tail#

Get the last n elements.

param int $n:

Number of elements to return (default: 10)

returns:

Series

first#

Get the first element.

returns:

mixed - First value

raises Polars\Exception:

If Series is empty

last#

Get the last element.

returns:

mixed - Last value

raises Polars\Exception:

If Series is empty

item#

Get a single value from the Series. The Series must contain exactly one element.

returns:

mixed - The scalar value

raises Polars\Exception:

If Series doesn’t have exactly one element

slice#

Extract a slice of the Series.

param int $offset:

Start index

param int $length:

Number of elements to include

returns:

Series

Example:

$s = new Series('x', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$s->head(3);     // Series [1, 2, 3]
$s->tail(3);     // Series [8, 9, 10]
$s->first();     // 1
$s->last();      // 10
$s->slice(2, 3); // Series [3, 4, 5]

$single = new Series('x', [42]);
$single->item(); // 42

Aggregations#

sum#

Get the sum of all values.

returns:

mixed - Sum value (int or float)

mean#

Get the mean of all values.

returns:

float

raises Polars\Exception:

If mean cannot be computed for this type

median#

Get the median of all values.

returns:

float

raises Polars\Exception:

If median cannot be computed for this type

min#

Get the minimum value.

returns:

mixed

max#

Get the maximum value.

returns:

mixed

std#

Get the standard deviation.

param int $ddof:

Delta degrees of freedom (default: 1 for sample std, use 0 for population std)

returns:

float

raises Polars\Exception:

If std cannot be computed for this type

variance#

Get the variance.

param int $ddof:

Delta degrees of freedom (default: 1 for sample variance, use 0 for population variance)

returns:

float

raises Polars\Exception:

If variance cannot be computed for this type

product#

Get the product of all values.

returns:

mixed

argMax#

Get the index of the maximum value.

returns:

int|null - Index of the maximum value, or null if the Series is empty

argMin#

Get the index of the minimum value.

returns:

int|null - Index of the minimum value, or null if the Series is empty

nanMax#

Get the maximum value, propagating NaN. If any value is NaN, returns NaN.

returns:

float

raises Polars\Exception:

If Series is not a float type

nanMin#

Get the minimum value, propagating NaN. If any value is NaN, returns NaN.

returns:

float

raises Polars\Exception:

If Series is not a float type

quantile#

Get the quantile value.

param float $quantile:

Quantile between 0.0 and 1.0

param string $method:

Interpolation method. One of: nearest, lower, higher, midpoint, linear, equiprobable (default: linear)

returns:

mixed - Quantile value

raises Polars\Exception:

If quantile is invalid or method is unknown

maxBy#

Get the value from this Series at the index of the maximum of another Series.

param Series $other:

Series to find the argMax of

returns:

mixed - Value at the index of the max of $other

raises Polars\Exception:

If $other is empty or index is out of bounds

minBy#

Get the value from this Series at the index of the minimum of another Series.

param Series $other:

Series to find the argMin of

returns:

mixed - Value at the index of the min of $other

raises Polars\Exception:

If $other is empty or index is out of bounds

mode#

Get the mode (most common value(s)). Returns a Series containing all values that appear most frequently.

returns:

Series - Series of modal values

raises Polars\Exception:

If mode cannot be computed for this type

implode#

Aggregate all values into a single list. Returns a Series of length 1 containing a list of all values.

returns:

Series - Series of length 1 with a list column

raises Polars\Exception:

If implode fails

Example:

$s = new Series('x', [1, 2, 3, 4, 5]);
$s->sum();      // 15
$s->mean();     // 3.0
$s->median();   // 3.0
$s->min();      // 1
$s->max();      // 5
$s->product();  // 120
$s->argMax();   // 4
$s->argMin();   // 0

$s2 = new Series('x', [2, 4, 4, 4, 5, 5, 7, 9]);
$s2->std(0);      // ~2.0 (population std)
$s2->variance(0); // ~4.0 (population variance)

$floats = new Series('x', [1.0, 2.0, NAN, 4.0]);
$floats->nanMax(); // NAN (propagates NaN)

$clean = new Series('x', [1.0, 2.0, 4.0]);
$clean->nanMax(); // 4.0
$clean->nanMin(); // 1.0
$clean->quantile(0.5);           // 2.0 (linear interpolation)
$clean->quantile(0.5, 'lower');  // 2.0
$clean->quantile(0.5, 'higher'); // 4.0

$values = new Series('values', [10, 20, 30, 40, 50]);
$keys   = new Series('keys',   [3, 1, 5, 2, 4]);
$values->maxBy($keys); // 30 (value at index of max in keys)
$values->minBy($keys); // 20 (value at index of min in keys)

$s3 = new Series('x', [1, 1, 2, 2, 2, 3]);
$s3->mode()->toArray(); // [2]

$s->implode()->len(); // 1

Null Handling#

countNonNull#

Count non-null values.

returns:

int

nullCount#

Count null values.

returns:

int

nUnique#

Count unique values (including null).

returns:

int

Example:

$s = new Series('x', [1, 2, null, 4, null]);
$s->countNonNull(); // 3
$s->nullCount();    // 2

$s2 = new Series('x', [1, 2, 2, 3, 3, 3]);
$s2->nUnique(); // 3

Descriptive Methods#

chunkLengths#

Get the length of each chunk.

returns:

array of int

nChunks#

Get the number of chunks.

returns:

int

estimatedSize#

Get the estimated memory size of the Series in bytes.

returns:

int

hasNulls#

Check if the Series contains any null values.

returns:

bool

hasValidity#

Check if the Series has a validity bitmap (i.e. may contain nulls).

returns:

bool

isDuplicated#

Get a boolean mask of duplicated values.

returns:

Series (boolean)

isUnique#

Get a boolean mask of unique (non-duplicated) values.

returns:

Series (boolean)

isFirstDistinct#

Get a boolean mask marking the first occurrence of each distinct value.

returns:

Series (boolean)

isLastDistinct#

Get a boolean mask marking the last occurrence of each distinct value.

returns:

Series (boolean)

isFinite#

Get a boolean mask of finite values (numeric Series only; NaN is not finite).

returns:

Series (boolean)

isInfinite#

Get a boolean mask of infinite values (numeric Series only).

returns:

Series (boolean)

isSorted#

Check if the Series is sorted.

param bool $descending:

Check for descending order instead

returns:

bool

isIn#

Check which values are present in another Series or array.

param Series|array $other:

Values to check membership against

param bool $nullsEqual:

Treat nulls as equal to nulls

returns:

Series (boolean)

Example:

$s = new Series('x', [1, 2, 3, 4]);
$s->isIn([2, 4])->toArray(); // [false, true, false, true]

lowerBound#

Get the minimal value that the Series dtype can hold.

returns:

mixed

upperBound#

Get the maximal value that the Series dtype can hold.

returns:

mixed

uniqueCounts#

Get the count of each unique value, in order of appearance.

returns:

Series (integer)

valueCounts#

Get a DataFrame with the unique values of the Series and a count column.

param bool $sort:

Sort by count descending

param bool $parallel:

Run in parallel

param string $countName:

Name of the count column

param bool $normalize:

Return fractions instead of counts

returns:

DataFrame with columns ["<name>", $countName]

describe#

Get a DataFrame with descriptive statistics of the Series. Numeric Series get count, null_count, mean, std, min, 25%, 50%, 75%, max rows (float values); other Series get count, null_count, min, max rows (string values).

returns:

DataFrame with columns ["statistic", "<name>"]

Example:

$s = new Series('x', [1, 2, 3, 4, 5]);
$s->describe()->getSeries('statistic')->toArray();
// ['count', 'null_count', 'mean', 'std', 'min', '25%', '50%', '75%', 'max']

Boolean Operations#

isNull#

Check which values are null.

returns:

Series - Boolean Series

isNotNull#

Check which values are not null.

returns:

Series - Boolean Series

isNan#

Check which values are NaN (for float Series).

returns:

Series - Boolean Series

raises Polars\Exception:

If Series is not float type

isNotNan#

Check which values are not NaN.

returns:

Series - Boolean Series

raises Polars\Exception:

If Series is not float type

any#

Check if any value is true (for boolean Series).

returns:

bool

raises Polars\Exception:

If Series is not boolean type

all#

Check if all values are true (for boolean Series).

returns:

bool

raises Polars\Exception:

If Series is not boolean type

Example:

$s = new Series('x', [1, null, 3]);
$s->isNull();    // Series [false, true, false]
$s->isNotNull(); // Series [true, false, true]

$bools = new Series('x', [true, false, true]);
$bools->any(); // true
$bools->all(); // false

Comparison Operations#

eq#

Element-wise equality comparison.

param mixed $other:

Value to compare (int, float, string, bool, or null)

returns:

Series - Boolean Series

ne#

Element-wise inequality comparison.

param mixed $other:

Value to compare

returns:

Series - Boolean Series

lt#

Element-wise less than comparison.

param mixed $other:

Value to compare

returns:

Series - Boolean Series

le#

Element-wise less than or equal comparison.

param mixed $other:

Value to compare

returns:

Series - Boolean Series

gt#

Element-wise greater than comparison.

param mixed $other:

Value to compare

returns:

Series - Boolean Series

ge#

Element-wise greater than or equal comparison.

param mixed $other:

Value to compare

returns:

Series - Boolean Series

Example:

$s = new Series('x', [1, 2, 3, 4, 5]);
$s->eq(3);  // Series [false, false, true, false, false]
$s->ne(3);  // Series [true, true, false, true, true]
$s->lt(3);  // Series [true, true, false, false, false]
$s->le(3);  // Series [true, true, true, false, false]
$s->gt(3);  // Series [false, false, false, true, true]
$s->ge(3);  // Series [false, false, true, true, true]

Data Manipulation#

sort#

Sort the Series.

param bool $descending:

Sort in descending order (default: false)

param bool $nullsLast:

Place nulls at the end (default: true)

returns:

Series - Sorted Series

reverse#

Reverse the Series.

returns:

Series

unique#

Get unique values.

returns:

Series

dropNulls#

Remove null values.

returns:

Series

Example:

$s = new Series('x', [3, 1, 4, 1, 5, 9, 2, 6]);
$s->sort();                    // [1, 1, 2, 3, 4, 5, 6, 9]
$s->sort(descending: true);    // [9, 6, 5, 4, 3, 2, 1, 1]
$s->reverse();                 // [6, 2, 9, 5, 1, 4, 1, 3]
$s->unique();                  // [1, 2, 3, 4, 5, 6, 9]

$withNulls = new Series('x', [1, null, 2, null, 3]);
$withNulls->dropNulls(); // [1, 2, 3]

Modify / Select#

In-place methods#

The following methods mutate the Series in place (like Python) and return void:

Append another Series to this one.

Extend this Series with the values of another Series.

Clear the Series in place, keeping at most the first n elements (retains the dtype).

Extend the Series in place with n copies of a constant value.

Set value where the boolean mask is true.

Set values at the given index locations. indices and values must have equal length.

$s = new Series('x', [1, 2, 3]);
$s->append(new Series('y', [4, 5]));   // [1, 2, 3, 4, 5]
$s->extendConstant(9, 2);               // [1, 2, 3, 4, 5, 9, 9]
$s->clear(3);                           // [1, 2, 3]
$s->set(new Series('m', [true, false, true]), 0);        // [0, 2, 0]
$s->scatter([0, 2], new Series('v', [100, 300]));        // [100, 2, 300]

Selection and ordering#

Get the index values that would sort this Series.

Return the k largest elements.

Return the k smallest elements.

Return the k largest elements of this Series, selected by the k largest values of the by Series (array of Series). bottomKBy is the mirror image.

Filter elements by a boolean mask Series.

Take values by index. With nullOnOob: true, out-of-bounds indices produce null.

Take every nth value, starting at offset.

Get the first n elements (alias of head).

Create a new Series of length filled with the value at index.

Create a single chunk of memory. With inPlace: true mutates and returns null, otherwise returns a new Series.

Shift values by n indices; shifted-in values are null unless fillValue is given.

Where the boolean mask is true the value from this Series is kept, otherwise the value from $other.

$s = new Series('x', [3, 1, 4, 1, 5, 9, 2, 6]);
$s->argSort()->toArray();        // [1, 3, 6, 0, 2, 4, 7, 5]
$s->topK(3)->toArray();          // [9, 6, 5]
$s->bottomK(2)->toArray();       // [1, 1]
$s->gather([0, 2, 7])->toArray();// [3, 4, 6]
$s->gatherEvery(2, 1)->toArray();// [1, 1, 9, 6]
$s->limit(3)->toArray();         // [3, 1, 4]
(new Series('x', [10, 20, 30]))->newFromIndex(1, 2)->toArray(); // [20, 20]
$s->shift(2)->toArray();         // [null, null, 3, 1, 4, 1, 5, 9]

Numeric rounding#

Round up to the nearest integer value.

Round down to the nearest integer value.

Round floating point data by decimals digits. mode: halfToEven (default), halfAwayFromZero, toZero.

Round to digits significant figures.

Truncate numeric data toward zero to decimals decimal places.

Set values outside the given boundaries to the boundary value. Both bounds are nullable.

$f = new Series('f', [1.5, 2.7, -1.2]);
$f->ceil()->toArray();    // [2.0, 3.0, -1.0]
$f->floor()->toArray();   // [1.0, 2.0, -2.0]
$f->round(0)->toArray();  // [2.0, 3.0, -1.0]
$f->truncate(0)->toArray();// [1.0, 2.0, -1.0]
$s = new Series('x', [1, 5, 10]);
$s->clip(2, 8)->toArray();        // [2, 5, 8]
$s->clip(lowerBound: 2)->toArray();// [2, 5, 10]

Null / NaN handling#

Drop all floating point NaN values.

Fill NaN values with a fill value.

Fill null values with value (takes precedence) or a strategy: forward, backward, min, max, mean, zero, one. limit caps consecutive fills for forward/backward.

$f = new Series('f', [1.0, NAN, 3.0]);
$f->dropNans()->toArray();   // [1.0, 3.0]
$f->fillNan(0.0)->toArray(); // [1.0, 0.0, 3.0]

$s = new Series('x', [1, null, null, 4]);
$s->fillNull(0)->toArray();                      // [1, 0, 0, 4]
$s->fillNull(strategy: 'forward')->toArray();    // [1, 1, 1, 4]
$s->fillNull(strategy: 'backward', limit: 1)->toArray(); // [1, null, 4, 4]

Binning#

Bin continuous values into discrete categories delimited by breaks.

Bin continuous values into categories based on their quantiles.

$s = new Series('x', [1, 3, 5, 7, 9]);
$s->cut([4.0, 6.0])->toArray();                          // ['[-inf, 4)', '[-inf, 4)', '[4, 6)', '[6, inf)', '[6, inf)']
$s->cut([4.0, 6.0], labels: ['low', 'mid', 'high'])->toArray(); // ['low', 'low', 'mid', 'high', 'high']
(new Series('x', [1, 2, 3, 4]))->qcut([0.5], labels: ['low', 'high'])->toArray(); // ['low', 'low', 'high', 'high']

Interpolation#

Interpolate intermediate values. method: linear (default) or nearest.

Interpolate using x-coordinates from another Series.

$s = new Series('x', [1.0, null, 3.0, null, 5.0]);
$s->interpolate()->toArray(); // [1.0, 2.0, 3.0, 4.0, 5.0]

Reshape / explode / run-length#

Reshape to a flat Series (single dimension, -1 infers) or an Array Series (multiple dimensions).

Explode a list Series into a flat Series.

Repeat elements as specified by an integer Series. Returns a List Series.

Run-length encode: returns a struct Series with len/run fields.

Get a distinct integer ID for each run of identical values.

$s = new Series('x', [1, 2, 3, 4, 5, 6]);
$s->reshape([-1])->toArray();      // [1, 2, 3, 4, 5, 6]
$s->reshape([2, 3])->len();        // 2 (Array Series)
(new Series('x', [1, 2, 3]))->implode()->explode()->toArray(); // [1, 2, 3]
(new Series('x', [1, 2, 3]))->repeatBy(new Series('b', [2, 0, 1]))->explode()->toArray(); // [1, 1, 3]
(new Series('x', [1, 1, 2, 2, 2, 3]))->rleId()->toArray(); // [0, 0, 1, 1, 1, 2]
(new Series('x', [1, 1, 2, 2, 2, 3]))->rle()->len();       // 3

Sampling#

Randomly sample by count (n) or fraction (which overrides n). seed makes the result reproducible.

Shuffle the contents of the Series.

$s = new Series('x', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$s->sample(n: 4, seed: 42)->len();        // 4
$s->sample(fraction: 0.5, seed: 1)->len(); // 5
$s->shuffle(42)->len();                   // 10

Memory and dtype#

Shrink numeric Series to the minimal required datatype.

Shrink Series memory usage (in place).

(new Series('x', [1, 2, 300]))->shrinkDtype()->dtype; // i32

SQL and dummies#

Execute a SQL query against the Series (registered as a single-column table named self by default). Returns a DataFrame.

Get dummy/indicator variables. Returns a DataFrame.

$s = new Series('x', [3, 1, 4, 1, 5]);
$df = $s->sql('SELECT x, x * 10 AS x10 FROM self WHERE x > 1 ORDER BY x');
$df->columns; // ['x', 'x10']

(new Series('c', ['a', 'b', 'a']))->toDummies()->columns; // ['c_a', 'c_b']

Fill Null Methods#

fillNullForward#

Fill null values using forward fill strategy.

returns:

Series

fillNullBackward#

Fill null values using backward fill strategy.

returns:

Series

fillNullMean#

Fill null values with the mean.

returns:

Series

fillNullZero#

Fill null values with zero.

returns:

Series

Example:

$s = new Series('x', [1, null, null, 4, null]);
$s->fillNullForward();  // [1, 1, 1, 4, 4]
$s->fillNullBackward(); // [1, 4, 4, 4, null]
$s->fillNullMean();     // [1, 2.5, 2.5, 4, 2.5]
$s->fillNullZero();     // [1, 0, 0, 4, 0]

Utility Methods#

toArray#

Convert Series to PHP array.

returns:

array

rename#

Rename the Series. Returns a new Series (original unchanged).

param string $name:

New name

returns:

Series

alias#

Create an alias for the Series (same as rename).

param string $name:

New name

returns:

Series

copy#

Create a copy of the Series.

returns:

Series

cast#

Cast Series to a different data type.

param string $dtype:

Target type. One of: ‘int8’, ‘int16’, ‘int32’, ‘int64’, ‘uint8’, ‘uint16’, ‘uint32’, ‘uint64’, ‘float32’, ‘float64’, ‘bool’, ‘string’

returns:

Series

raises Polars\Exception:

If cast fails

__toString#

Return a formatted string representation of the Series.

Example:

$s = new Series('x', [1, 2, 3]);
$s->toArray();       // [1, 2, 3]
$s->rename('y');     // Series named 'y'
$s->alias('z');      // Series named 'z'
$s->cast('float64'); // Series with float values

echo $s;
// shape: (3,)
// Series: 'x' [i64]
// [
//     1
//     2
//     3
// ]