Struct numpy::array::PyArray [−][src]
pub struct PyArray<T, D>(_, _, _);
Expand description
A safe, static-typed interface for NumPy ndarray.
Memory location
- Case1: Constructed via
IntoPyArray
orfrom_vec
orfrom_owned_array
.
These methods don’t allocate memory and use Box<[T]>
as a internal buffer.
Please take care that you cannot use some destructive methods like resize
,
for this kind of array.
- Case2: Constructed via other methods, like
ToPyArray
orfrom_slice
orfrom_array
.
These methods allocate memory in Python’s private heap.
In both cases, PyArray is managed by Python GC. So you can neither retrieve it nor deallocate it manually.
Reference
Like new
, all constractor methods of PyArray
returns &PyArray
.
This design follows pyo3’s ownership concept.
Data type and Dimension
PyArray
has 2 type parametes T
and D
. T
represents its data type like
f32
, and D
represents its dimension.
All data types you can use implements Element.
Dimensions are represented by ndarray’s Dimension trait.
Typically, you can use Ix1, Ix2, ..
for fixed size arrays, and use IxDyn
for dynamic
dimensioned arrays. They’re re-exported from ndarray
crate.
You can also use various type aliases we provide, like PyArray1
or PyArrayDyn
.
To specify concrete dimension like 3×4×5
, you can use types which implements ndarray’s
IntoDimension
trait. Typically, you can use array(e.g. [3, 4, 5]
) or tuple(e.g. (3, 4, 5)
) as a dimension.
Example
use numpy::PyArray; use ndarray::Array; pyo3::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
Gets a raw PyArrayObject
pointer.
Returns dtype
of the array.
Counterpart of array.dtype
in Python.
Example
pyo3::Python::with_gil(|py| { let array = numpy::PyArray::from_vec(py, vec![1, 2, 3i32]); let dtype = array.dtype(); assert_eq!(dtype.get_datatype().unwrap(), numpy::DataType::Int32); });
Returns a temporally unwriteable reference of the array.
Returns true
if the internal data of the array is C-style contiguous
(default of numpy and ndarray) or Fortran-style contiguous.
Example
use pyo3::types::IntoPyDict; pyo3::Python::with_gil(|py| { let array = numpy::PyArray::arange(py, 0, 10, 1); assert!(array.is_contiguous()); let locals = [("np", numpy::get_array_module(py).unwrap())].into_py_dict(py); let not_contiguous: &numpy::PyArray1<f32> = py .eval("np.zeros((3, 5))[::2, 4]", Some(locals), None) .unwrap() .downcast() .unwrap(); assert!(!not_contiguous.is_contiguous()); });
Returns true
if the internal data of the array is Fortran-style contiguous.
Returns true
if the internal data of the array is C-style contiguous.
Get Py<PyArray>
from &PyArray
, which is the owned wrapper of PyObject.
You can use this method when you have to avoid lifetime annotation to your function args
or return types, like used with pyo3’s pymethod
.
Example
use numpy::PyArray1; fn return_py_array() -> pyo3::Py<PyArray1<i32>> { pyo3::Python::with_gil(|py| PyArray1::zeros(py, [5], false).to_owned()) } let array = return_py_array(); pyo3::Python::with_gil(|py| { assert_eq!(array.as_ref(py).readonly().as_slice().unwrap(), &[0, 0, 0, 0, 0]); });
Constructs PyArray
from raw python object without incrementing reference counts.
Constructs PyArray from raw python object and increments reference counts.
Returns the number of dimensions in the array.
Same as numpy.ndarray.ndim
Example
use numpy::PyArray3; pyo3::Python::with_gil(|py| { let arr = PyArray3::<f64>::new(py, [4, 5, 6], false); assert_eq!(arr.ndim(), 3); });
Returns a slice which contains how many bytes you need to jump to the next row.
Same as numpy.ndarray.strides
Example
use numpy::PyArray3; pyo3::Python::with_gil(|py| { let arr = PyArray3::<f64>::new(py, [4, 5, 6], false); assert_eq!(arr.strides(), &[240, 48, 8]); });
Returns a slice which contains dimmensions of the array.
Same as numpy.ndarray.shape
Example
use numpy::PyArray3; pyo3::Python::with_gil(|py| { let arr = PyArray3::<f64>::new(py, [4, 5, 6], false); assert_eq!(arr.shape(), &[4, 5, 6]); });
Creates a new uninitialized PyArray in python heap.
If is_fortran == true
, returns Fortran-order array. Else, returns C-order array.
Example
use numpy::PyArray3; pyo3::Python::with_gil(|py| { let arr = PyArray3::<i32>::new(py, [4, 5, 6], false); assert_eq!(arr.shape(), &[4, 5, 6]); });
Construct a new nd-dimensional array filled with 0.
If is_fortran
is true, then
a fortran order array is created, otherwise a C-order array is created.
See also PyArray_Zeros
Example
use numpy::PyArray2; pyo3::Python::with_gil(|py| { let pyarray: &PyArray2<usize> = PyArray2::zeros(py, [2, 2], false); assert_eq!(pyarray.readonly().as_array(), array![[0, 0], [0, 0]]); });
Returns the immutable view of the internal data of PyArray
as slice.
Please consider the use of safe alternatives
(PyReadonlyArray::as_slice
, as_cell_slice
or to_vec
) instead of this.
Safety
If the internal array is not readonly and can be mutated from Python code, holding the slice might cause undefined behavior.
Returns the view of the internal data of PyArray
as &[Cell<T>]
.
Returns the view of the internal data of PyArray
as mutable slice.
Safety
If another reference to the internal data exists(e.g., &[T]
or ArrayView
),
it might cause undefined behavior.
In such case, please consider the use of as_cell_slice
,
Construct PyArray from
ndarray::Array
.
This method uses internal Vec
of ndarray::Array
as numpy array.
Example
use numpy::PyArray; pyo3::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]]); });
Get the immutable reference of the specified element, with checking the passed index is valid.
Please consider the use of safe alternatives
(PyReadonlyArray::get
or get_owned
) instead of this.
Example
use numpy::PyArray; pyo3::Python::with_gil(|py| { let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap(); assert_eq!(*unsafe { arr.get([1, 0, 3]) }.unwrap(), 11); });
Safety
If the internal array is not readonly and can be mutated from Python code, holding the slice might cause undefined behavior.
Get the immutable reference of the specified element, without checking the passed index is valid.
See NpyIndex for what types you can use as index.
Passing an invalid index can cause undefined behavior(mostly SIGSEGV).
Example
use numpy::PyArray; pyo3::Python::with_gil(|py| { let arr = PyArray::arange(py, 0, 16, 1).reshape([2, 2, 4]).unwrap(); assert_eq!(unsafe { *arr.uget([1, 0, 3]) }, 11); });
Same as uget, but returns &mut T
.
Get dynamic dimensioned array from fixed dimension array.
Returns the copy of the internal data of PyArray
to Vec
.
Returns ErrorKind::NotContiguous
if the internal array is not contiguous.
See also as_slice
Example
use numpy::PyArray2; use pyo3::types::IntoPyDict; pyo3::Python::with_gil(|py| { let locals = [("np", numpy::get_array_module(py).unwrap())].into_py_dict(py); let array: &PyArray2<i64> = py .eval("np.array([[0, 1], [2, 3]], dtype='int64')", Some(locals), None) .unwrap() .downcast() .unwrap(); assert_eq!(array.to_vec().unwrap(), vec![0, 1, 2, 3]); });
Construct PyArray from ndarray::ArrayBase
.
This method allocates memory in Python’s heap via numpy api, and then copies all elements of the array there.
Example
use numpy::PyArray; pyo3::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]]); });
Get the immutable view of the internal data of PyArray
, as
ndarray::ArrayView
.
Please consider the use of safe alternatives
(PyReadonlyArray::as_array
or to_array
) instead of this.
Safety
If the internal array is not readonly and can be mutated from Python code,
holding the ArrayView
might cause undefined behavior.
Get a copy of PyArray
as
ndarray::Array
.
Example
use numpy::PyArray; pyo3::Python::with_gil(|py| { let py_array = PyArray::arange(py, 0, 4, 1).reshape([2, 2]).unwrap(); assert_eq!( py_array.to_owned_array(), array![[0, 1], [2, 3]] ) });
Construct one-dimension PyArray from slice.
Example
use numpy::PyArray; let array = [1, 2, 3, 4, 5]; pyo3::Python::with_gil(|py| { let pyarray = PyArray::from_slice(py, &array); assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]); });
Construct one-dimension PyArray from a type which implements
ExactSizeIterator
.
Example
use numpy::PyArray; use std::collections::BTreeSet; let vec = vec![1, 2, 3, 4, 5]; pyo3::Python::with_gil(|py| { let pyarray = PyArray::from_exact_iter(py, vec.iter().map(|&x| x)); assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]); });
Construct one-dimension PyArray from a type which implements
IntoIterator
.
If no reliable size_hint
is available,
this method can allocate memory multiple time, which can hurt performance.
Example
use numpy::PyArray; let set: std::collections::BTreeSet<u32> = [4, 3, 2, 5, 1].into_iter().cloned().collect(); pyo3::Python::with_gil(|py| { let pyarray = PyArray::from_iter(py, set); assert_eq!(pyarray.readonly().as_slice().unwrap(), &[1, 2, 3, 4, 5]); });
Extends or trancates the length of 1 dimension PyArray.
Example
use numpy::PyArray; pyo3::Python::with_gil(|py| { let pyarray = PyArray::arange(py, 0, 10, 1); assert_eq!(pyarray.len(), 10); pyarray.resize(100).unwrap(); assert_eq!(pyarray.len(), 100); });
Iterates all elements of this array. See NpySingleIter for more.
Construct a two-dimension PyArray from Vec<Vec<T>>
.
This function checks all dimension of inner vec, and if there’s any vec
where its dimension differs from others, it returns ArrayCastError
.
Example
use numpy::PyArray; let vec2 = vec![vec![1, 2, 3]; 2]; pyo3::Python::with_gil(|py| { let pyarray = PyArray::from_vec2(py, &vec2).unwrap(); assert_eq!(pyarray.readonly().as_array(), array![[1, 2, 3], [1, 2, 3]]); assert!(PyArray::from_vec2(py, &[vec![1], vec![2, 3]]).is_err()); });
Construct a three-dimension PyArray from Vec<Vec<Vec<T>>>
.
This function checks all dimension of inner vec, and if there’s any vec where its dimension differs from others, it returns error.
Example
use numpy::PyArray; let vec3 = vec![vec![vec![1, 2]; 2]; 2]; pyo3::Python::with_gil(|py| { let pyarray = PyArray::from_vec3(py, &vec3).unwrap(); assert_eq!( pyarray.readonly().as_array(), array![[[1, 2], [1, 2]], [[1, 2], [1, 2]]] ); assert!(PyArray::from_vec3(py, &[vec![vec![1], vec![]]]).is_err()); });
Copies self into other
, performing a data-type conversion if necessary.
Example
use numpy::PyArray; pyo3::Python::with_gil(|py| { let pyarray_f = PyArray::arange(py, 2.0, 5.0, 1.0); let pyarray_i = 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]); });
Cast the PyArray<T>
to PyArray<U>
, by allocating a new array.
Example
use numpy::PyArray; pyo3::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!(pyarray_f.copy_to(pyarray_i).is_ok()); assert_eq!(pyarray_i.readonly().as_slice().unwrap(), &[2, 3, 4]); });
Construct a new array which has same values as self, same matrix order, but has different
dimensions specified by dims
.
Since a returned array can contain a same pointer as self, we highly recommend to drop an
old array, if this method returns Ok
.
Example
use numpy::PyArray; pyo3::Python::with_gil(|py| { let array = PyArray::from_exact_iter(py, 0..9); let array = array.reshape([3, 3]).unwrap(); assert_eq!(array.readonly().as_array(), array![[0, 1, 2], [3, 4, 5], [6, 7, 8]]); assert!(array.reshape([5]).is_err()); });
pub fn reshape_with_order<'py, ID, D2>(
&'py self,
dims: ID,
order: NPY_ORDER
) -> PyResult<&'py PyArray<T, D2>> where
ID: IntoDimension<Dim = D2>,
D2: Dimension,
[src]
pub fn reshape_with_order<'py, ID, D2>(
&'py self,
dims: ID,
order: NPY_ORDER
) -> PyResult<&'py PyArray<T, D2>> where
ID: IntoDimension<Dim = D2>,
D2: Dimension,
[src]Same as reshape, but you can change the order of returned matrix.
Return evenly spaced values within a given interval. Same as numpy.arange.
See also PyArray_Arange.
Example
use numpy::PyArray; pyo3::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]); });
Methods from Deref<Target = PyAny>
Convert this PyAny to a concrete Python type.
Determines whether this object has the given attribute.
This is equivalent to the Python expression hasattr(self, attr_name)
.
Retrieves an attribute value.
This is equivalent to the Python expression self.attr_name
.
pub fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> where
V: ToBorrowedObject,
N: ToBorrowedObject,
[src]
pub fn setattr<N, V>(&self, attr_name: N, value: V) -> Result<(), PyErr> where
V: ToBorrowedObject,
N: ToBorrowedObject,
[src]Sets an attribute value.
This is equivalent to the Python expression self.attr_name = value
.
Deletes an attribute.
This is equivalent to the Python expression del self.attr_name
.
Compares two Python objects.
This is equivalent to:
if self == other:
return Equal
elif a < b:
return Less
elif a > b:
return Greater
else:
raise TypeError("PyAny::compare(): All comparisons returned false")
pub fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp
) -> Result<&PyAny, PyErr> where
O: ToPyObject,
[src]
pub fn rich_compare<O>(
&self,
other: O,
compare_op: CompareOp
) -> Result<&PyAny, PyErr> where
O: ToPyObject,
[src]Compares two Python objects.
Depending on the value of compare_op
, this is equivalent to one of the
following Python expressions:
- CompareOp::Eq:
self == other
- CompareOp::Ne:
self != other
- CompareOp::Lt:
self < other
- CompareOp::Le:
self <= other
- CompareOp::Gt:
self > other
- CompareOp::Ge:
self >= other
Determines whether this object is callable.
Calls the object.
This is equivalent to the Python expression self(*args, **kwargs)
.
Calls the object without arguments.
This is equivalent to the Python expression self()
.
Calls the object with only positional arguments.
This is equivalent to the Python expression self(*args)
.
Calls a method on the object.
This is equivalent to the Python expression self.name(*args, **kwargs)
.
Example
use pyo3::types::IntoPyDict; let gil = Python::acquire_gil(); let py = gil.python(); let list = vec![3, 6, 5, 4, 7].to_object(py); let dict = vec![("reverse", true)].into_py_dict(py); list.call_method(py, "sort", (), Some(dict)).unwrap(); assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3]); let new_element = 1.to_object(py); list.call_method(py, "append", (new_element,), None).unwrap(); assert_eq!(list.extract::<Vec<i32>>(py).unwrap(), vec![7, 6, 5, 4, 3, 1]);
Calls a method on the object without arguments.
This is equivalent to the Python expression self.name()
.
Calls a method on the object with only positional arguments.
This is equivalent to the Python expression self.name(*args)
.
Returns whether the object is considered to be true.
This is equivalent to the Python expression bool(self)
.
Returns whether the object is considered to be None.
This is equivalent to the Python expression self is None
.
Returns true if the sequence or mapping has a length of 0.
This is equivalent to the Python expression len(self) == 0
.
Gets an item from the collection.
This is equivalent to the Python expression self[key]
.
pub fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> where
K: ToBorrowedObject,
V: ToBorrowedObject,
[src]
pub fn set_item<K, V>(&self, key: K, value: V) -> Result<(), PyErr> where
K: ToBorrowedObject,
V: ToBorrowedObject,
[src]Sets a collection item value.
This is equivalent to the Python expression self[key] = value
.
Deletes an item from the collection.
This is equivalent to the Python expression del self[key]
.
Takes an object and returns an iterator for it.
This is typically a new iterator but if the argument is an iterator, this returns itself.
Returns the Python type pointer for this object.
Casts the PyObject to a concrete Python object type.
This can cast only to native Python types, not types implemented in Rust.
Extracts some type from the Python object.
This is a wrapper function around FromPyObject::extract()
.
Returns the reference count for the Python object.
Computes the “repr” representation of self.
This is equivalent to the Python expression repr(self)
.
Computes the “str” representation of self.
This is equivalent to the Python expression str(self)
.
Retrieves the hash code of self.
This is equivalent to the Python expression hash(self)
.
Returns the length of the sequence or mapping.
This is equivalent to the Python expression len(self)
.
Returns the list of attributes of this object.
This is equivalent to the Python expression dir(self)
.
Checks whether this object is an instance of type T
.
This is equivalent to the Python expression isinstance(self, T)
.
Trait Implementations
Performs the conversion.
type Layout = PyArrayObject
type Layout = PyArrayObject
Layout
type BaseLayout = PyObject
type BaseLayout = PyObject
Layout of Basetype.
type Initializer = PyNativeTypeInitializer<Self>
type Initializer = PyNativeTypeInitializer<Self>
Initializer for layout
type AsRefTarget = Self
type AsRefTarget = Self
Utility type to make Py::as_ref work
PyTypeObject instance for this type.
Checks if object
is an instance of this type or a subclass of this type.
Class doc string
Checks if object
is an instance of this type.
Auto Trait Implementations
impl<T, D> !RefUnwindSafe for PyArray<T, D>
impl<T, D> UnwindSafe for PyArray<T, D> where
D: UnwindSafe,
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
Convert from an arbitrary PyObject
. Read more
Convert from an arbitrary borrowed PyObject
. Read more
Convert from an arbitrary PyObject
or panic. Read more
Convert from an arbitrary PyObject
or panic. Read more
Convert from an arbitrary PyObject
. Read more
Convert from an arbitrary borrowed PyObject
. Read more
Convert from an arbitrary borrowed PyObject
. Read more
Cast from a concrete Python object type to PyObject.
pub fn try_from_exact<V>(value: V) -> Result<&'v T, PyDowncastError<'v>> where
V: Into<&'v PyAny>,
[src]
pub fn try_from_exact<V>(value: V) -> Result<&'v T, PyDowncastError<'v>> where
V: Into<&'v PyAny>,
[src]Cast from a concrete Python object type to PyObject. With exact type check.
Returns the safe abstraction over the type object.