polars.Series.to_numpy#

Series.to_numpy(
*,
writable: bool = False,
allow_copy: bool = True,
masked: bool = False,
) → ndarray[Any, Any][source]#

Convert this Series to a NumPy ndarray.

This operation copies data only when necessary. The conversion is zero copy when all of the following hold:

  • The data type is an integer, float, Datetime, Duration, or Array.

  • The Series contains no null values.

  • The Series consists of a single chunk.

  • The writable parameter is set to False (default).

Parameters:
writable

Ensure the resulting array is writable. This will force a copy of the data if the array was created without copy as the underlying Arrow data is immutable.

allow_copy

Allow memory to be copied to perform the conversion. If set to False, causes conversions that are not zero-copy to fail.

masked

Return a numpy.ma.MaskedArray in which null values are masked. The data keeps the type it would have without nulls, and the values under the mask are unspecified. Nulls inside nested values are converted as they are without masked, except for Array and Struct values. writable and allow_copy only apply to the data, not the mask.

Warning

This functionality is considered unstable. It may be changed at any point without it being considered a breaking change.

Examples

Numeric data without nulls can be converted without copying data. The resulting array will not be writable.

>>> s = pl.Series([1, 2, 3], dtype=pl.Int8)
>>> arr = s.to_numpy()
>>> arr
array([1, 2, 3], dtype=int8)
>>> arr.flags.writeable
False

Set writable=True to force data copy to make the array writable.

>>> s.to_numpy(writable=True).flags.writeable
True

Integer Series containing nulls will be cast to a float type with nan representing a null value. This requires data to be copied.

>>> s = pl.Series([1, 2, None], dtype=pl.UInt16)
>>> s.to_numpy()
array([ 1.,  2., nan], dtype=float32)

Set allow_copy=False to raise an error if data would be copied.

>>> s.to_numpy(allow_copy=False)  
Traceback (most recent call last):
...
RuntimeError: copy not allowed: cannot convert to a NumPy array without copying data

Series of data type Array and Struct will result in an array with more than one dimension.

>>> s = pl.Series([[1, 2, 3], [4, 5, 6]], dtype=pl.Array(pl.Int64, 3))
>>> s.to_numpy()
array([[1, 2, 3],
       [4, 5, 6]])

Set masked=True to represent null values with a mask instead, which preserves the data type.

>>> s = pl.Series([1, 2, None], dtype=pl.UInt16)
>>> arr = s.to_numpy(masked=True)
>>> arr.dtype
dtype('uint16')
>>> arr.mask
array([False, False,  True])