polars.Series.to_numpy#
- Series.to_numpy( ) 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, orArray.The Series contains no null values.
The Series consists of a single chunk.
The
writableparameter is set toFalse(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.MaskedArrayin 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 withoutmasked, except forArrayandStructvalues.writableandallow_copyonly 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=Trueto 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
nanrepresenting 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=Falseto 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
ArrayandStructwill 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=Trueto 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])