pub trait PyArrayMethods<'py, T, D>: PyUntypedArrayMethods<'py> {
Show 31 methods
// Required methods
fn as_untyped(&self) -> &Bound<'py, PyUntypedArray>;
fn data(&self) -> *mut T;
unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
where T: Element,
D: Dimension;
unsafe fn get_mut(&self, index: impl NpyIndex<Dim = D>) -> Option<&mut T>
where T: Element,
D: Dimension;
fn get_owned<Idx>(&self, index: Idx) -> Option<T>
where T: Element,
D: Dimension,
Idx: NpyIndex<Dim = D>;
fn to_dyn(&self) -> &Bound<'py, PyArray<T, IxDyn>>
where T: Element,
D: Dimension;
fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
where T: Element,
D: Dimension;
fn try_readonly(&self) -> Result<PyReadonlyArray<'py, T, D>, BorrowError>
where T: Element,
D: Dimension;
fn try_readwrite(&self) -> Result<PyReadwriteArray<'py, T, D>, BorrowError>
where T: Element,
D: Dimension;
unsafe fn as_array(&self) -> ArrayView<'_, T, D>
where T: Element,
D: Dimension;
unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
where T: Element,
D: Dimension;
fn as_raw_array(&self) -> RawArrayView<T, D>
where T: Element,
D: Dimension;
fn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
where T: Element,
D: Dimension;
fn to_owned_array(&self) -> Array<T, D>
where T: Element,
D: Dimension;
fn copy_to<U: Element>(
&self,
other: &Bound<'py, PyArray<U, D>>,
) -> PyResult<()>
where T: Element;
fn cast<U: Element>(
&self,
is_fortran: bool,
) -> PyResult<Bound<'py, PyArray<U, D>>>
where T: Element;
fn permute<ID: IntoDimension>(
&self,
axes: Option<ID>,
) -> PyResult<Bound<'py, PyArray<T, D>>>
where T: Element;
fn reshape_with_order<ID: IntoDimension>(
&self,
shape: ID,
order: NPY_ORDER,
) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>
where T: Element;
unsafe fn resize<ID: IntoDimension>(&self, newshape: ID) -> PyResult<()>
where T: Element;
unsafe fn try_as_matrix<R, C, RStride, CStride>(
&self,
) -> Option<MatrixView<'_, T, R, C, RStride, CStride>>
where T: Scalar + Element,
D: Dimension,
R: Dim,
C: Dim,
RStride: Dim,
CStride: Dim;
unsafe fn try_as_matrix_mut<R, C, RStride, CStride>(
&self,
) -> Option<MatrixViewMut<'_, T, R, C, RStride, CStride>>
where T: Scalar + Element,
D: Dimension,
R: Dim,
C: Dim,
RStride: Dim,
CStride: Dim;
// Provided methods
fn dims(&self) -> D
where D: Dimension { ... }
unsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>
where T: Element,
D: Dimension { ... }
unsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>
where T: Element,
D: Dimension { ... }
unsafe fn uget<Idx>(&self, index: Idx) -> &T
where T: Element,
D: Dimension,
Idx: NpyIndex<Dim = D> { ... }
unsafe fn uget_mut<Idx>(&self, index: Idx) -> &mut T
where T: Element,
D: Dimension,
Idx: NpyIndex<Dim = D> { ... }
unsafe fn uget_raw<Idx>(&self, index: Idx) -> *mut T
where T: Element,
D: Dimension,
Idx: NpyIndex<Dim = D> { ... }
fn readonly(&self) -> PyReadonlyArray<'py, T, D>
where T: Element,
D: Dimension { ... }
fn readwrite(&self) -> PyReadwriteArray<'py, T, D>
where T: Element,
D: Dimension { ... }
fn transpose(&self) -> PyResult<Bound<'py, PyArray<T, D>>>
where T: Element { ... }
fn reshape<ID: IntoDimension>(
&self,
shape: ID,
) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>
where T: Element { ... }
}
Expand description
Implementation of functionality for PyArray<T, D>
.
Required Methods§
Sourcefn as_untyped(&self) -> &Bound<'py, PyUntypedArray>
fn as_untyped(&self) -> &Bound<'py, PyUntypedArray>
Access an untyped representation of this array.
Sourceunsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
unsafe fn get(&self, index: impl NpyIndex<Dim = D>) -> Option<&T>
Get a reference of the specified element if the given index is valid.
§Safety
Calling this method is undefined behaviour if the underlying array
is aliased mutably by other instances of PyArray
or concurrently modified by Python or other native code.
Consider using safe alternatives like PyReadonlyArray::get
.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
assert_eq!(unsafe { *pyarray.get([1, 0, 3]).unwrap() }, 11);
});
Sourceunsafe fn get_mut(&self, index: impl NpyIndex<Dim = D>) -> Option<&mut T>
unsafe fn get_mut(&self, index: impl NpyIndex<Dim = D>) -> Option<&mut T>
Same as get
, but returns Option<&mut T>
.
§Safety
Calling this method is undefined behaviour if the underlying array
is aliased immutably or mutably by other instances of PyArray
or concurrently modified by Python or other native code.
Consider using safe alternatives like PyReadwriteArray::get_mut
.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
unsafe {
*pyarray.get_mut([1, 0, 3]).unwrap() = 42;
}
assert_eq!(unsafe { *pyarray.get([1, 0, 3]).unwrap() }, 42);
});
Sourcefn get_owned<Idx>(&self, index: Idx) -> Option<T>
fn get_owned<Idx>(&self, index: Idx) -> Option<T>
Get a copy of the specified element in the array.
See NpyIndex
for what types can be used as the index.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
assert_eq!(pyarray.get_owned([1, 0, 3]), Some(11));
});
Sourcefn to_dyn(&self) -> &Bound<'py, PyArray<T, IxDyn>>
fn to_dyn(&self) -> &Bound<'py, PyArray<T, IxDyn>>
Turn an array with fixed dimensionality into one with dynamic dimensionality.
Sourcefn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
fn to_vec(&self) -> Result<Vec<T>, NotContiguousError>
Returns a copy of the internal data of the array as a Vec
.
Fails if the internal array is not contiguous. See also as_slice
.
§Example
use numpy::{PyArray2, PyArrayMethods};
use pyo3::{Python, types::PyAnyMethods, ffi::c_str};
Python::with_gil(|py| {
let pyarray= py
.eval(c_str!("__import__('numpy').array([[0, 1], [2, 3]], dtype='int64')"), None, None)?
.downcast_into::<PyArray2<i64>>()?;
assert_eq!(pyarray.to_vec()?, vec![0, 1, 2, 3]);
})
Sourcefn try_readonly(&self) -> Result<PyReadonlyArray<'py, T, D>, BorrowError>
fn try_readonly(&self) -> Result<PyReadonlyArray<'py, T, D>, BorrowError>
Get an immutable borrow of the NumPy array
Sourcefn try_readwrite(&self) -> Result<PyReadwriteArray<'py, T, D>, BorrowError>
fn try_readwrite(&self) -> Result<PyReadwriteArray<'py, T, D>, BorrowError>
Get a mutable borrow of the NumPy array
Sourceunsafe fn as_array(&self) -> ArrayView<'_, T, D>
unsafe fn as_array(&self) -> ArrayView<'_, T, D>
Returns an ArrayView
of the internal array.
See also PyReadonlyArray::as_array
.
§Safety
Calling this method invalidates all exclusive references to the internal data, e.g. &mut [T]
or ArrayViewMut
.
Sourceunsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
unsafe fn as_array_mut(&self) -> ArrayViewMut<'_, T, D>
Returns an ArrayViewMut
of the internal array.
See also PyReadwriteArray::as_array_mut
.
§Safety
Calling this method invalidates all other references to the internal data, e.g. ArrayView
or ArrayViewMut
.
Sourcefn as_raw_array(&self) -> RawArrayView<T, D>
fn as_raw_array(&self) -> RawArrayView<T, D>
Returns the internal array as RawArrayView
enabling element access via raw pointers
Sourcefn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
fn as_raw_array_mut(&self) -> RawArrayViewMut<T, D>
Returns the internal array as RawArrayViewMut
enabling element access via raw pointers
Sourcefn to_owned_array(&self) -> Array<T, D>
fn to_owned_array(&self) -> Array<T, D>
Get a copy of the array as an ndarray::Array
.
§Example
use numpy::{PyArray, PyArrayMethods};
use ndarray::array;
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap();
assert_eq!(
pyarray.to_owned_array(),
array![[0, 1], [2, 3]]
)
});
Sourcefn copy_to<U: Element>(&self, other: &Bound<'py, PyArray<U, D>>) -> PyResult<()>where
T: Element,
fn copy_to<U: Element>(&self, other: &Bound<'py, PyArray<U, D>>) -> PyResult<()>where
T: Element,
Copies self
into other
, performing a data type conversion if necessary.
See also PyArray_CopyInto
.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0);
let pyarray_i = unsafe { PyArray::<i64, _>::new(py, [3], false) };
assert!(pyarray_f.copy_to(&pyarray_i).is_ok());
assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]);
});
Sourcefn cast<U: Element>(
&self,
is_fortran: bool,
) -> PyResult<Bound<'py, PyArray<U, D>>>where
T: Element,
fn cast<U: Element>(
&self,
is_fortran: bool,
) -> PyResult<Bound<'py, PyArray<U, D>>>where
T: Element,
Cast the PyArray<T>
to PyArray<U>
, by allocating a new array.
See also PyArray_CastToType
.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0);
let pyarray_i = pyarray_f.cast::<i32>(false).unwrap();
assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]);
});
Sourcefn permute<ID: IntoDimension>(
&self,
axes: Option<ID>,
) -> PyResult<Bound<'py, PyArray<T, D>>>where
T: Element,
fn permute<ID: IntoDimension>(
&self,
axes: Option<ID>,
) -> PyResult<Bound<'py, PyArray<T, D>>>where
T: Element,
A view of self
with a different order of axes determined by axes
.
If axes
is None
, the order of axes is reversed which corresponds to the standard matrix transpose.
See also numpy.transpose
and PyArray_Transpose
.
§Example
use numpy::prelude::*;
use numpy::PyArray;
use pyo3::Python;
use ndarray::array;
Python::with_gil(|py| {
let array = array![[0, 1, 2], [3, 4, 5]].into_pyarray(py);
let array = array.permute(Some([1, 0])).unwrap();
assert_eq!(array.readonly().as_array(), array![[0, 3], [1, 4], [2, 5]]);
});
Sourcefn reshape_with_order<ID: IntoDimension>(
&self,
shape: ID,
order: NPY_ORDER,
) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>where
T: Element,
fn reshape_with_order<ID: IntoDimension>(
&self,
shape: ID,
order: NPY_ORDER,
) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>where
T: Element,
Construct a new array which has same values as self
,
but has different dimensions specified by shape
and a possibly different memory order specified by order
.
See also numpy.reshape
and PyArray_Newshape
.
§Example
use numpy::prelude::*;
use numpy::{npyffi::NPY_ORDER, PyArray};
use pyo3::Python;
use ndarray::array;
Python::with_gil(|py| {
let array =
PyArray::from_iter(py, 0..9).reshape_with_order([3, 3], NPY_ORDER::NPY_FORTRANORDER).unwrap();
assert_eq!(array.readonly().as_array(), array![[0, 3, 6], [1, 4, 7], [2, 5, 8]]);
assert!(array.is_fortran_contiguous());
assert!(array.reshape([5]).is_err());
});
Sourceunsafe fn resize<ID: IntoDimension>(&self, newshape: ID) -> PyResult<()>where
T: Element,
unsafe fn resize<ID: IntoDimension>(&self, newshape: ID) -> PyResult<()>where
T: Element,
Extends or truncates the dimensions of an array.
This method works only on contiguous arrays.
Missing elements will be initialized as if calling zeros
.
See also ndarray.resize
and PyArray_Resize
.
§Safety
There should be no outstanding references (shared or exclusive) into the array as this method might re-allocate it and thereby invalidate all pointers into it.
§Example
use numpy::prelude::*;
use numpy::PyArray;
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::<f64, _>::zeros(py, (10, 10), false);
assert_eq!(pyarray.shape(), [10, 10]);
unsafe {
pyarray.resize((100, 100)).unwrap();
}
assert_eq!(pyarray.shape(), [100, 100]);
});
Sourceunsafe fn try_as_matrix<R, C, RStride, CStride>(
&self,
) -> Option<MatrixView<'_, T, R, C, RStride, CStride>>
unsafe fn try_as_matrix<R, C, RStride, CStride>( &self, ) -> Option<MatrixView<'_, T, R, C, RStride, CStride>>
Try to convert this array into a nalgebra::MatrixView
using the given shape and strides.
§Safety
Calling this method invalidates all exclusive references to the internal data, e.g. ArrayViewMut
or MatrixSliceMut
.
Sourceunsafe fn try_as_matrix_mut<R, C, RStride, CStride>(
&self,
) -> Option<MatrixViewMut<'_, T, R, C, RStride, CStride>>
unsafe fn try_as_matrix_mut<R, C, RStride, CStride>( &self, ) -> Option<MatrixViewMut<'_, T, R, C, RStride, CStride>>
Try to convert this array into a nalgebra::MatrixViewMut
using the given shape and strides.
§Safety
Calling this method invalidates all other references to the internal data, e.g. ArrayView
, MatrixSlice
, ArrayViewMut
or MatrixSliceMut
.
Provided Methods§
Sourcefn dims(&self) -> Dwhere
D: Dimension,
fn dims(&self) -> Dwhere
D: Dimension,
Same as [shape
][PyUntypedArray::shape], but returns D
instead of &[usize]
.
Sourceunsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>
unsafe fn as_slice(&self) -> Result<&[T], NotContiguousError>
Returns an immutable view of the internal data as a slice.
§Safety
Calling this method is undefined behaviour if the underlying array
is aliased mutably by other instances of PyArray
or concurrently modified by Python or other native code.
Please consider the safe alternative PyReadonlyArray::as_slice
.
Sourceunsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>
unsafe fn as_slice_mut(&self) -> Result<&mut [T], NotContiguousError>
Returns a mutable view of the internal data as a slice.
§Safety
Calling this method is undefined behaviour if the underlying array
is aliased immutably or mutably by other instances of PyArray
or concurrently modified by Python or other native code.
Please consider the safe alternative PyReadwriteArray::as_slice_mut
.
Sourceunsafe fn uget<Idx>(&self, index: Idx) -> &T
unsafe fn uget<Idx>(&self, index: Idx) -> &T
Get an immutable reference of the specified element, without checking the given index.
See NpyIndex
for what types can be used as the index.
§Safety
Passing an invalid index is undefined behavior. The element must also have been initialized and all other references to it is must also be shared.
See PyReadonlyArray::get
for a safe alternative.
§Example
use numpy::{PyArray, PyArrayMethods};
use pyo3::Python;
Python::with_gil(|py| {
let pyarray = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap();
assert_eq!(unsafe { *pyarray.uget([1, 0, 3]) }, 11);
});
Sourceunsafe fn uget_mut<Idx>(&self, index: Idx) -> &mut T
unsafe fn uget_mut<Idx>(&self, index: Idx) -> &mut T
Same as uget
, but returns &mut T
.
§Safety
Passing an invalid index is undefined behavior. The element must also have been initialized and other references to it must not exist.
See PyReadwriteArray::get_mut
for a safe alternative.
Sourcefn readonly(&self) -> PyReadonlyArray<'py, T, D>
fn readonly(&self) -> PyReadonlyArray<'py, T, D>
Get an immutable borrow of the NumPy array
§Panics
Panics if the allocation backing the array is currently mutably borrowed.
For a non-panicking variant, use try_readonly
.
Sourcefn readwrite(&self) -> PyReadwriteArray<'py, T, D>
fn readwrite(&self) -> PyReadwriteArray<'py, T, D>
Get a mutable borrow of the NumPy array
§Panics
Panics if the allocation backing the array is currently borrowed or if the array is flagged as not writeable.
For a non-panicking variant, use try_readwrite
.
Sourcefn transpose(&self) -> PyResult<Bound<'py, PyArray<T, D>>>where
T: Element,
fn transpose(&self) -> PyResult<Bound<'py, PyArray<T, D>>>where
T: Element,
Special case of permute
which reverses the order the axes.
Sourcefn reshape<ID: IntoDimension>(
&self,
shape: ID,
) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>where
T: Element,
fn reshape<ID: IntoDimension>(
&self,
shape: ID,
) -> PyResult<Bound<'py, PyArray<T, ID::Dim>>>where
T: Element,
Special case of reshape_with_order
which keeps the memory order the same.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.