Rust Numpy库按行迭代:无法生成返回行而不是单个值的NPYSingleterBuilder::readwrite

2024-10-02 16:31:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Numpy数组上按行进行迭代。数组是通过PyO3访问的,我认为库可以访问底层的C对象,但是我似乎找不到更复杂的SingleIteratorBuilder的参考,它可以帮助我通过行访问数组

这是文档页面:https://docs.rs/numpy/0.12.1/numpy/npyiter/struct.NpySingleIterBuilder.html#method.readwrite (我看这个项目还处于起步阶段)

这是我的rust代码,它被编译成python模块

#[macro_use]
extern crate std;
extern crate ndarray;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use numpy::*;

#[pyfunction]
fn array_print(_py: Python<'_>,  matrix1: &PyArray2<i32> ){
     let matrix1_iter = NpySingleIterBuilder::readonly(matrix1.readonly()).build().unwrap();
 
    for i in matrix1_iter{
        println!("{}", i);
    };
}

/// A Python module implemented in Rust.
#[pymodule]
fn algo_match(_py: Python<'_>, m: &PyModule) -> PyResult<()> { 
    m.add_function(wrap_pyfunction!(array_print, m)?)?;
    Ok(())
}

本例的python代码

#matrixes is the name of the compiled Rust module
import matrixes as am 

arr1 = np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]], ndmin=2)
am.array_print(arr1)

这就是我刚才说的

~project>python use_algorithm.py
1
2
3
4
5
6
1
2
3
4
5
6

当然,我尝试使用ndarray并将整个pyArray复制到一个新对象中,但这是最糟糕的情况,因为我的矩阵在行和列上都应该很大。复制数据可能是更糟糕的选择


Tags: 对象代码pynumpyuseextern数组array
1条回答
网友
1楼 · 发布于 2024-10-02 16:31:33

如果数组是连续的,则可以访问.as_slice()。将矩阵视为一个简单切片,可以使用.chunks(n)对行进行迭代

这只适用于对行进行迭代。对于列,您可能需要itertools

#[macro_use]
extern crate std;
extern crate ndarray;
use numpy::*;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

#[pyfunction]
fn array_print(_py: Python<'_>, matrix1: &PyArray2<i64>) {
    let row_length = matrix1.shape()[1];
    for row in matrix1.readonly().as_slice().unwrap().chunks(row_length) {
        println!("{:?}", row);
    }
}

/// A Python module implemented in Rust.
#[pymodule]
fn matrixes(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(array_print, m)?)?;
    Ok(())
}

相关问题 更多 >