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

    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};
use pyo3::Python;

Python::with_gil(|py| {
    let py_array = vec![1, 2, 3].to_pyarray(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::{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(py);

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

Required Associated Types

The element type of resulting array.

The dimension type of the resulting array.

Required Methods

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

Implementations on Foreign Types

Implementors