pub struct PyArray<T, D>(/* private fields */);
Expand description
A safe, statically-typed wrapper for NumPy’s ndarray
class.
§Memory location
- Allocated by Rust: Constructed via
IntoPyArray
orfrom_vec
orfrom_owned_array
.
These methods transfers ownership of the Rust allocation into a suitable Python object and uses the memory as the internal buffer backing the NumPy array.
Please note that some destructive methods like [resize
][Self::resize] will fail
when used with this kind of array as NumPy cannot reallocate the internal buffer.
- Allocated by NumPy: Constructed via other methods, like
ToPyArray
orfrom_slice
orfrom_array
.
These methods allocate memory in Python’s private heap via NumPy’s API.
In both cases, PyArray
is managed by Python so it can neither be moved from
nor deallocated manually.
§References
Like new
, all constructor methods of PyArray
return a shared reference &PyArray
instead of an owned value. This design follows PyO3’s ownership concept,
i.e. the return value is GIL-bound owning reference into Python’s heap.
§Element type and dimensionality
PyArray
has two type parametes T
and D
.
T
represents the type of its elements, e.g. f32
or [PyObject
].
D
represents its dimensionality, e.g Ix2
or IxDyn
.
Element types are Rust types which implement the Element
trait.
Dimensions are represented by the ndarray::Dimension
trait.
Typically, Ix1, Ix2, ...
are used for fixed dimensionality arrays,
and IxDyn
is used for dynamic dimensionality arrays. Type aliases
for combining PyArray
with these types are provided, e.g. PyArray1
or PyArrayDyn
.
To specify concrete dimension like 3×4×5
, types which implement the ndarray::IntoDimension
trait are used. Typically, this means arrays like [3, 4, 5]
or tuples like (3, 4, 5)
.
§Example
use numpy::{PyArray, PyArrayMethods};
use ndarray::{array, Array};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0., 4., 1.).reshape([2, 2]).unwrap();
let array = array![[3., 4.], [5., 6.]];
assert_eq!(
array.dot(&pyarray.readonly().as_array()),
array![[8., 15.], [12., 23.]]
);
});
Implementations§
Source§impl<T: Element, D: Dimension> PyArray<T, D>
impl<T: Element, D: Dimension> PyArray<T, D>
Sourcepub unsafe fn new<'py, ID>(
py: Python<'py>,
dims: ID,
is_fortran: bool,
) -> Bound<'py, Self>where
ID: IntoDimension<Dim = D>,
pub unsafe fn new<'py, ID>(
py: Python<'py>,
dims: ID,
is_fortran: bool,
) -> Bound<'py, Self>where
ID: IntoDimension<Dim = D>,
Creates a new uninitialized NumPy array.
If is_fortran
is true, then it has Fortran/column-major order,
otherwise it has C/row-major order.
§Safety
The returned array will always be safe to be dropped as the elements must either
be trivially copyable (as indicated by <T as Element>::IS_COPY
) or be pointers
into Python’s heap, which NumPy will automatically zero-initialize.
However, the elements themselves will not be valid and should be initialized manually
using raw pointers obtained via [uget_raw
][Self::uget_raw]. Before that, all methods
which produce references to the elements invoke undefined behaviour. In particular,
zero-initialized pointers are not valid instances of PyObject
.
§Example
use numpy::prelude::*;
use numpy::PyArray3;
use pyo3::Python;
Python::with_gil(|py| {
let arr = unsafe {
let arr = PyArray3::<i32>::new(py, [4, 5, 6], false);
for i in 0..4 {
for j in 0..5 {
for k in 0..6 {
arr.uget_raw([i, j, k]).write((i * j * k) as i32);
}
}
}
arr
};
assert_eq!(arr.shape(), &[4, 5, 6]);
});
Sourcepub unsafe fn new_bound<'py, ID>(
py: Python<'py>,
dims: ID,
is_fortran: bool,
) -> Bound<'py, Self>where
ID: IntoDimension<Dim = D>,
👎Deprecated since 0.23.0: renamed to PyArray::new
pub unsafe fn new_bound<'py, ID>(
py: Python<'py>,
dims: ID,
is_fortran: bool,
) -> Bound<'py, Self>where
ID: IntoDimension<Dim = D>,
PyArray::new
Sourcepub unsafe fn borrow_from_array<'py, S>(
array: &ArrayBase<S, D>,
container: Bound<'py, PyAny>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
pub unsafe fn borrow_from_array<'py, S>(
array: &ArrayBase<S, D>,
container: Bound<'py, PyAny>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
Creates a NumPy array backed by array
and ties its ownership to the Python object container
.
The resulting NumPy array will be writeable from Python space. If this is undesireable, use PyReadwriteArray::make_nonwriteable.
§Safety
container
is set as a base object of the returned array which must not be dropped until container
is dropped.
Furthermore, array
must not be reallocated from the time this method is called and until container
is dropped.
§Example
#[pyclass]
struct Owner {
array: Array1<f64>,
}
#[pymethods]
impl Owner {
#[getter]
fn array<'py>(this: Bound<'py, Self>) -> Bound<'py, PyArray1<f64>> {
let array = &this.borrow().array;
// SAFETY: The memory backing `array` will stay valid as long as this object is alive
// as we do not modify `array` in any way which would cause it to be reallocated.
unsafe { PyArray1::borrow_from_array(array, this.into_any()) }
}
}
Sourcepub unsafe fn borrow_from_array_bound<'py, S>(
array: &ArrayBase<S, D>,
container: Bound<'py, PyAny>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
👎Deprecated since 0.23.0: renamed to PyArray::borrow_from_array
pub unsafe fn borrow_from_array_bound<'py, S>(
array: &ArrayBase<S, D>,
container: Bound<'py, PyAny>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
PyArray::borrow_from_array
Sourcepub fn zeros<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> Bound<'_, Self>where
ID: IntoDimension<Dim = D>,
pub fn zeros<ID>(py: Python<'_>, dims: ID, is_fortran: bool) -> Bound<'_, Self>where
ID: IntoDimension<Dim = D>,
Construct a new NumPy array filled with zeros.
If is_fortran
is true, then it has Fortran/column-major order,
otherwise it has C/row-major order.
For arrays of Python objects, this will fill the array with valid pointers to zero-valued Python integer objects.
See also numpy.zeros
and PyArray_Zeros
.
§Example
use numpy::{PyArray2, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray2::<usize>::zeros(py, [2, 2], true);
assert_eq!(pyarray.readonly().as_slice().unwrap(), [0; 4]);
});
Sourcepub fn zeros_bound<ID>(
py: Python<'_>,
dims: ID,
is_fortran: bool,
) -> Bound<'_, Self>where
ID: IntoDimension<Dim = D>,
👎Deprecated since 0.23.0: renamed to PyArray::zeros
pub fn zeros_bound<ID>(
py: Python<'_>,
dims: ID,
is_fortran: bool,
) -> Bound<'_, Self>where
ID: IntoDimension<Dim = D>,
PyArray::zeros
Deprecated name for PyArray::zeros
.
Sourcepub fn from_owned_array(py: Python<'_>, arr: Array<T, D>) -> Bound<'_, Self>
pub fn from_owned_array(py: Python<'_>, arr: Array<T, D>) -> Bound<'_, Self>
Constructs a NumPy from an ndarray::Array
This method uses the internal Vec
of the ndarray::Array
as the base object of the NumPy array.
§Example
use numpy::{PyArray, PyArrayMethods};
use ndarray::array;
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::from_owned_array(py, array![[1, 2], [3, 4]]);
assert_eq!(pyarray.readonly().as_array(), array![[1, 2], [3, 4]]);
});
Sourcepub fn from_owned_array_bound(
py: Python<'_>,
arr: Array<T, D>,
) -> Bound<'_, Self>
👎Deprecated since 0.23.0: renamed to PyArray::from_owned_array
pub fn from_owned_array_bound( py: Python<'_>, arr: Array<T, D>, ) -> Bound<'_, Self>
PyArray::from_owned_array
Deprecated name for PyArray::from_owned_array
.
Sourcepub fn from_array<'py, S>(
py: Python<'py>,
arr: &ArrayBase<S, D>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
pub fn from_array<'py, S>(
py: Python<'py>,
arr: &ArrayBase<S, D>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
Construct a NumPy array from a ndarray::ArrayBase
.
This method allocates memory in Python’s heap via the NumPy API, and then copies all elements of the array there.
§Example
use numpy::{PyArray, PyArrayMethods};
use ndarray::array;
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::from_array(py, &array![[1, 2], [3, 4]]);
assert_eq!(pyarray.readonly().as_array(), array![[1, 2], [3, 4]]);
});
Sourcepub fn from_array_bound<'py, S>(
py: Python<'py>,
arr: &ArrayBase<S, D>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
👎Deprecated since 0.23.0: renamed to PyArray::from_array
pub fn from_array_bound<'py, S>(
py: Python<'py>,
arr: &ArrayBase<S, D>,
) -> Bound<'py, Self>where
S: Data<Elem = T>,
PyArray::from_array
Deprecated name for PyArray::from_array
.
Source§impl<D: Dimension> PyArray<PyObject, D>
impl<D: Dimension> PyArray<PyObject, D>
Sourcepub fn from_owned_object_array<T>(
py: Python<'_>,
arr: Array<Py<T>, D>,
) -> Bound<'_, Self>
pub fn from_owned_object_array<T>( py: Python<'_>, arr: Array<Py<T>, D>, ) -> Bound<'_, Self>
Construct a NumPy array containing objects stored in a ndarray::Array
This method uses the internal Vec
of the ndarray::Array
as the base object of the NumPy array.
§Example
use ndarray::array;
use pyo3::{pyclass, Py, Python, types::PyAnyMethods};
use numpy::{PyArray, PyArrayMethods};
#[pyclass]
struct CustomElement {
foo: i32,
bar: f64,
}
Python::with_gil(|py| {
let array = array![
Py::new(py, CustomElement {
foo: 1,
bar: 2.0,
}).unwrap(),
Py::new(py, CustomElement {
foo: 3,
bar: 4.0,
}).unwrap(),
];
let pyarray = PyArray::from_owned_object_array(py, array);
assert!(pyarray.readonly().as_array().get(0).unwrap().bind(py).is_instance_of::<CustomElement>());
});
Sourcepub fn from_owned_object_array_bound<T>(
py: Python<'_>,
arr: Array<Py<T>, D>,
) -> Bound<'_, Self>
👎Deprecated since 0.23.0: renamed to PyArray::from_owned_object_array
pub fn from_owned_object_array_bound<T>( py: Python<'_>, arr: Array<Py<T>, D>, ) -> Bound<'_, Self>
PyArray::from_owned_object_array
Deprecated name for PyArray::from_owned_object_array
.
Source§impl<T: Element> PyArray<T, Ix1>
impl<T: Element> PyArray<T, Ix1>
Sourcepub fn from_slice<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self>
pub fn from_slice<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self>
Sourcepub fn from_slice_bound<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self>
👎Deprecated since 0.23.0: renamed to PyArray::from_slice
pub fn from_slice_bound<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self>
PyArray::from_slice
Deprecated name for PyArray::from_slice
.
Sourcepub fn from_vec_bound<'py>(py: Python<'py>, vec: Vec<T>) -> Bound<'py, Self>
👎Deprecated since 0.23.0: renamed to PyArray::from_vec
pub fn from_vec_bound<'py>(py: Python<'py>, vec: Vec<T>) -> Bound<'py, Self>
PyArray::from_vec
Deprecated name for PyArray::from_vec
.
Sourcepub fn from_iter<I>(py: Python<'_>, iter: I) -> Bound<'_, Self>where
I: IntoIterator<Item = T>,
pub fn from_iter<I>(py: Python<'_>, iter: I) -> Bound<'_, Self>where
I: IntoIterator<Item = T>,
Construct a one-dimensional array from an Iterator
.
If no reliable size_hint
is available,
this method can allocate memory multiple times, which can hurt performance.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::from_iter(py, "abcde".chars().map(u32::from));
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[97, 98, 99, 100, 101]);
});
Sourcepub fn from_iter_bound<I>(py: Python<'_>, iter: I) -> Bound<'_, Self>where
I: IntoIterator<Item = T>,
👎Deprecated since 0.23.0: renamed to PyArray::from_iter
pub fn from_iter_bound<I>(py: Python<'_>, iter: I) -> Bound<'_, Self>where
I: IntoIterator<Item = T>,
PyArray::from_iter
Deprecated name for PyArray::from_iter
.
Source§impl<T: Element> PyArray<T, Ix2>
impl<T: Element> PyArray<T, Ix2>
Sourcepub fn from_vec2<'py>(
py: Python<'py>,
v: &[Vec<T>],
) -> Result<Bound<'py, Self>, FromVecError>
pub fn from_vec2<'py>( py: Python<'py>, v: &[Vec<T>], ) -> Result<Bound<'py, Self>, FromVecError>
Construct a two-dimension array from a Vec<Vec<T>>
.
This function checks all dimensions of the inner vectors and returns an error if they are not all equal.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
use ndarray::array;
Python::with_gil(|py| {
let vec2 = vec![vec![11, 12], vec![21, 22]];
let pyarray = PyArray::from_vec2(py, &vec2).unwrap();
assert_eq!(pyarray.readonly().as_array(), array![[11, 12], [21, 22]]);
let ragged_vec2 = vec![vec![11, 12], vec![21]];
assert!(PyArray::from_vec2(py, &ragged_vec2).is_err());
});
Sourcepub fn from_vec2_bound<'py>(
py: Python<'py>,
v: &[Vec<T>],
) -> Result<Bound<'py, Self>, FromVecError>
👎Deprecated since 0.23.0: renamed to PyArray::from_vec2
pub fn from_vec2_bound<'py>( py: Python<'py>, v: &[Vec<T>], ) -> Result<Bound<'py, Self>, FromVecError>
PyArray::from_vec2
Deprecated name for PyArray::from_vec2
.
Source§impl<T: Element> PyArray<T, Ix3>
impl<T: Element> PyArray<T, Ix3>
Sourcepub fn from_vec3<'py>(
py: Python<'py>,
v: &[Vec<Vec<T>>],
) -> Result<Bound<'py, Self>, FromVecError>
pub fn from_vec3<'py>( py: Python<'py>, v: &[Vec<Vec<T>>], ) -> Result<Bound<'py, Self>, FromVecError>
Construct a three-dimensional array from a Vec<Vec<Vec<T>>>
.
This function checks all dimensions of the inner vectors and returns an error if they are not all equal.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
use ndarray::array;
Python::with_gil(|py| {
let vec3 = vec![
vec![vec![111, 112], vec![121, 122]],
vec![vec![211, 212], vec![221, 222]],
];
let pyarray = PyArray::from_vec3(py, &vec3).unwrap();
assert_eq!(
pyarray.readonly().as_array(),
array![[[111, 112], [121, 122]], [[211, 212], [221, 222]]]
);
let ragged_vec3 = vec![
vec![vec![111, 112], vec![121, 122]],
vec![vec![211], vec![221, 222]],
];
assert!(PyArray::from_vec3(py, &ragged_vec3).is_err());
});
Sourcepub fn from_vec3_bound<'py>(
py: Python<'py>,
v: &[Vec<Vec<T>>],
) -> Result<Bound<'py, Self>, FromVecError>
👎Deprecated since 0.23.0: renamed to PyArray::from_vec3
pub fn from_vec3_bound<'py>( py: Python<'py>, v: &[Vec<Vec<T>>], ) -> Result<Bound<'py, Self>, FromVecError>
PyArray::from_vec3
Deprecated name for PyArray::from_vec3
.
Source§impl<T: Element + AsPrimitive<f64>> PyArray<T, Ix1>
impl<T: Element + AsPrimitive<f64>> PyArray<T, Ix1>
Sourcepub fn arange<'py>(
py: Python<'py>,
start: T,
stop: T,
step: T,
) -> Bound<'py, Self>
pub fn arange<'py>( py: Python<'py>, start: T, stop: T, step: T, ) -> Bound<'py, Self>
Return evenly spaced values within a given interval.
See numpy.arange for the Python API and PyArray_Arange for the C API.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 2.0, 4.0, 0.5);
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[2.0, 2.5, 3.0, 3.5]);
let pyarray = PyArray::arange(py, -2, 4, 3);
assert_eq!(pyarray.readonly().as_slice().unwrap(), &[-2, 1]);
});
Sourcepub fn arange_bound<'py>(
py: Python<'py>,
start: T,
stop: T,
step: T,
) -> Bound<'py, Self>
👎Deprecated since 0.23.0: renamed to PyArray::arange
pub fn arange_bound<'py>( py: Python<'py>, start: T, stop: T, step: T, ) -> Bound<'py, Self>
PyArray::arange
Deprecated name for PyArray::arange
.
Trait Implementations§
Source§impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D>
impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D>
Source§fn type_object_raw<'py>(py: Python<'py>) -> *mut PyTypeObject
fn type_object_raw<'py>(py: Python<'py>) -> *mut PyTypeObject
Source§fn is_type_of(ob: &Bound<'_, PyAny>) -> bool
fn is_type_of(ob: &Bound<'_, PyAny>) -> bool
object
is an instance of this type or a subclass of this type.§fn type_object(py: Python<'_>) -> Bound<'_, PyType>
fn type_object(py: Python<'_>) -> Bound<'_, PyType>
§fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>
fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>
PyTypeInfo::type_object
PyTypeInfo::type_object
].§fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool
fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool
PyTypeInfo::is_type_of
PyTypeInfo::is_type_of
].§fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool
fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool
object
is an instance of this type.§fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool
fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool
PyTypeInfo::is_exact_type_of
PyTypeInfo::is_exact_type_of
].impl<T, D> DerefToPyAny for PyArray<T, D>
Auto Trait Implementations§
impl<T, D> !Freeze for PyArray<T, D>
impl<T, D> !RefUnwindSafe for PyArray<T, D>
impl<T, D> !Send for PyArray<T, D>
impl<T, D> !Sync for PyArray<T, D>
impl<T, D> Unpin for PyArray<T, D>
impl<T, D> UnwindSafe for PyArray<T, D>where
T: UnwindSafe,
D: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> PyTypeCheck for Twhere
T: PyTypeInfo,
impl<T> PyTypeCheck for Twhere
T: PyTypeInfo,
§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self
from the equivalent element of its
superset. Read more§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self
is actually part of its subset T
(and can be converted to it).§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset
but without any property checks. Always succeeds.§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self
to the equivalent element of its superset.