python - Rust Numpy 库 - 按行迭代:无法构建返回行而不是单个值的 NpySingleIterBuilder::readwrite

标签 python numpy rust iterator pyo3

我正在尝试在 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 复制到一个新对象中,但这是最糟糕的情况,因为我的矩阵在行和列上都应该很大。复制数据可能是更糟糕的选择。

最佳答案

您可以访问.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(())
}

关于python - Rust Numpy 库 - 按行迭代:无法构建返回行而不是单个值的 NpySingleIterBuilder::readwrite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65191873/

相关文章:

python - 忽略 NaN 的 Pandas 聚合

python - 调整 numpy 或数据集大小的有效方法?

rust - Rust 中有传统风格的 switch 语句吗?

rust - 如何处理 "multiple applicable items in scope"错误?

python - 从 SConscript 确定构建目录

python - 累积列,而其他列在 Pandas 中没有变化

python - 从给定其对等点的 numpy 子数组中获取一个数字

struct - 如果我创建一个结构并将其放入向量中,它是驻留在堆上还是堆栈上?

python - 在docker中使用pip安装python mysqlclient时出现 'OSError: mysql_config not found'错误

python - 如何在 Tkinter 中高效创建大型条目网格?