Skip to content

Commit f592b97

Browse files
committed
Add PyArray::to_owned_array
1 parent a0e1521 commit f592b97

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/array.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,28 @@ impl<T: TypeNum, D: Dimension> PyArray<T, D> {
464464
unsafe { ArrayViewMut::from_shape_ptr(self.ndarray_shape(), self.data()) }
465465
}
466466

467+
/// Get a copy of `PyArray` as
468+
/// [`ndarray::Array`](https://docs.rs/ndarray/0.12/ndarray/type.Array.html).
469+
///
470+
/// # Example
471+
/// ```
472+
/// # #[macro_use] extern crate ndarray; extern crate pyo3; extern crate numpy; fn main() {
473+
/// use numpy::PyArray;
474+
/// let gil = pyo3::Python::acquire_gil();
475+
/// let py_array = PyArray::arange(gil.python(), 0, 4, 1).reshape([2, 2]).unwrap();
476+
/// assert_eq!(
477+
/// py_array.to_owned_array(),
478+
/// array![[0, 1], [2, 3]]
479+
/// )
480+
/// # }
481+
/// ```
482+
pub fn to_owned_array(&self) -> Array<T, D> {
483+
unsafe {
484+
let vec = self.as_slice().to_owned();
485+
Array::from_shape_vec_unchecked(self.ndarray_shape(), vec)
486+
}
487+
}
488+
467489
/// Get an immutable reference of a specified element, without checking the
468490
/// passed index is valid.
469491
///

0 commit comments

Comments
 (0)