numpy::array

Struct PyArray

Source
pub struct PyArray<T, D>(/* private fields */);
Expand description

A safe, statically-typed wrapper for NumPy’s ndarray class.

§Memory location

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.

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>

Source

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]);
});
Source

pub 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

Deprecated name for PyArray::new.

§Safety

See PyArray::new.

Source

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()) }
    }
}
Source

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>,

👎Deprecated since 0.23.0: renamed to PyArray::borrow_from_array
Source

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]);
});
Source

pub 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

Deprecated name for PyArray::zeros.

Source

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]]);
});
Source

pub fn from_owned_array_bound( py: Python<'_>, arr: Array<T, D>, ) -> Bound<'_, Self>

👎Deprecated since 0.23.0: renamed to PyArray::from_owned_array

Deprecated name for PyArray::from_owned_array.

Source

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]]);
});
Source

pub 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

Deprecated name for PyArray::from_array.

Source§

impl<D: Dimension> PyArray<PyObject, D>

Source

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>());
});
Source

pub 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

Deprecated name for PyArray::from_owned_object_array.

Source§

impl<T: Element> PyArray<T, Ix1>

Source

pub fn from_slice<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self>

Construct a one-dimensional array from a slice.

§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;

Python::with_gil(|py| {
    let slice = &[1, 2, 3, 4, 5];
    let pyarray = PyArray::from_slice(py, slice);
    assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
});
Source

pub fn from_slice_bound<'py>(py: Python<'py>, slice: &[T]) -> Bound<'py, Self>

👎Deprecated since 0.23.0: renamed to PyArray::from_slice

Deprecated name for PyArray::from_slice.

Source

pub fn from_vec<'py>(py: Python<'py>, vec: Vec<T>) -> Bound<'py, Self>

Construct a one-dimensional array from a Vec<T>.

§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;

Python::with_gil(|py| {
    let vec = vec![1, 2, 3, 4, 5];
    let pyarray = PyArray::from_vec(py, vec);
    assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]);
});
Source

pub fn from_vec_bound<'py>(py: Python<'py>, vec: Vec<T>) -> Bound<'py, Self>

👎Deprecated since 0.23.0: renamed to PyArray::from_vec

Deprecated name for PyArray::from_vec.

Source

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]);
});
Source

pub 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

Deprecated name for PyArray::from_iter.

Source§

impl<T: Element> PyArray<T, Ix2>

Source

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());
});
Source

pub 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

Deprecated name for PyArray::from_vec2.

Source§

impl<T: Element> PyArray<T, Ix3>

Source

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());
});
Source

pub 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

Deprecated name for PyArray::from_vec3.

Source§

impl<T: Element + AsPrimitive<f64>> PyArray<T, Ix1>

Source

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]);
});
Source

pub 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

Deprecated name for PyArray::arange.

Trait Implementations§

Source§

impl<T: Element, D: Dimension> PyTypeInfo for PyArray<T, D>

Source§

const NAME: &'static str = "PyArray<T, D>"

Class name.
Source§

const MODULE: Option<&'static str>

Module name, if any.
Source§

fn type_object_raw<'py>(py: Python<'py>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
Source§

fn is_type_of(ob: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>

👎Deprecated since 0.23.0: renamed to PyTypeInfo::type_object
Deprecated name for [PyTypeInfo::type_object].
§

fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool

👎Deprecated since 0.23.0: renamed to PyTypeInfo::is_type_of
Deprecated name for [PyTypeInfo::is_type_of].
§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
§

fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool

👎Deprecated since 0.23.0: renamed to PyTypeInfo::is_exact_type_of
Deprecated name for [PyTypeInfo::is_exact_type_of].
Source§

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>
where T: Unpin, D: Unpin,

§

impl<T, D> UnwindSafe for PyArray<T, D>
where T: UnwindSafe, D: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

const NAME: &'static str = <T as PyTypeInfo>::NAME

Name of self. This is used in error messages, for example.
§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.