Trait numpy::convert::ToPyArray

source ·
pub trait ToPyArray {
    type Item: Element;
    type Dim: Dimension;

    // Required method
    fn to_pyarray_bound<'py>(
        &self,
        py: Python<'py>
    ) -> Bound<'py, PyArray<Self::Item, Self::Dim>>;

    // Provided method
    fn to_pyarray<'py>(
        &self,
        py: Python<'py>
    ) -> &'py PyArray<Self::Item, Self::Dim> { ... }
}
Expand description

Conversion trait from borrowing Rust types to PyArray.

This trait takes &self by reference, which means it allocates in Python heap and then copies the elements there.

§Examples

use numpy::{PyArray, ToPyArray, PyArrayMethods};
use pyo3::Python;

Python::with_gil(|py| {
    let py_array = vec![1, 2, 3].to_pyarray_bound(py);

    assert_eq!(py_array.readonly().as_slice().unwrap(), &[1, 2, 3]);
});

Due to copying the elments, this method converts non-contiguous arrays to C-order contiguous arrays.

use numpy::prelude::*;
use numpy::{PyArray, ToPyArray};
use ndarray::{arr3, s};
use pyo3::Python;

Python::with_gil(|py| {
    let array = arr3(&[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]);
    let py_array = array.slice(s![.., 0..1, ..]).to_pyarray_bound(py);

    assert_eq!(py_array.readonly().as_array(), arr3(&[[[1, 2, 3]], [[7, 8, 9]]]));
    assert!(py_array.is_c_contiguous());
});

Required Associated Types§

source

type Item: Element

The element type of resulting array.

source

type Dim: Dimension

The dimension type of the resulting array.

Required Methods§

source

fn to_pyarray_bound<'py>( &self, py: Python<'py> ) -> Bound<'py, PyArray<Self::Item, Self::Dim>>

Copies the content pointed to by &self into a newly allocated NumPy array.

Provided Methods§

source

fn to_pyarray<'py>( &self, py: Python<'py> ) -> &'py PyArray<Self::Item, Self::Dim>

👎Deprecated since 0.21.0: will be replaced by ToPyArray::to_pyarray_bound in the future

Deprecated form of ToPyArray::to_pyarray_bound

Implementations on Foreign Types§

source§

impl<N, R, C, S> ToPyArray for Matrix<N, R, C, S>
where N: Scalar + Element, R: Dim, C: Dim, S: Storage<N, R, C>,

source§

fn to_pyarray_bound<'py>( &self, py: Python<'py> ) -> Bound<'py, PyArray<Self::Item, Self::Dim>>

Note that the NumPy array always has Fortran memory layout matching the memory layout used by nalgebra.

§

type Item = N

§

type Dim = Dim<[usize; 2]>

source§

impl<S, D, A> ToPyArray for ArrayBase<S, D>
where S: Data<Elem = A>, D: Dimension, A: Element,

§

type Item = A

§

type Dim = D

source§

fn to_pyarray_bound<'py>( &self, py: Python<'py> ) -> Bound<'py, PyArray<Self::Item, Self::Dim>>

source§

impl<T: Element> ToPyArray for [T]

§

type Item = T

§

type Dim = Dim<[usize; 1]>

source§

fn to_pyarray_bound<'py>( &self, py: Python<'py> ) -> Bound<'py, PyArray<Self::Item, Self::Dim>>

Implementors§