是否可以使用Vec
而不是Slice
对象对Rust ndarray
矩阵中的列进行索引?我能找到的唯一文档是关于使用contiguous columns进行切片的
具体地说,我正在尝试用Python实现如下代码:
x = np.array([[1,2,3,4,5,6], [7,8,9,10,11,12]])
idx = [0,1,2,4]
x[:, idx]
x[:, idx]
的结果将是包含idx
中描述的所有行且仅包含列的矩阵的子集,即[0,1,2,4]
。
我目前正在使用ndarray
(顾名思义),但我找不到在非连续切片上设置子集的方法。例如,您可以传递ndarray
,它可以接受带有start
、stop
和index
的Slice
,但是我找不到一种方法来传递无法使用Slice
对象描述的列的列表。
例如:
#[macro_use]
extern crate ndarray;
fn main() {
let mut x = array![[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]];
let idx = vec![0, 1, 2, 4];
// The following works as expected
let y = x.slice(s![.., 0..2]);
println!("{:?}", y);
// This is conceptually what I would like to do but
// It does not work.
let y = x.slice(s![.., idx]);
}
发布于 2018-10-17 03:46:31
与Numpy中的“高级索引”类似的是ArrayBase::select()
方法:
use ndarray::{array, Axis};
fn main() {
let x = array![[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]];
let idx = vec![0, 1, 2, 4];
println!("{}", x.select(Axis(1), &idx));
}
生成输出
[[1, 2, 3, 5],
[7, 8, 9, 11]]
请注意,结果数组是所选元素的副本(就像在Numpy中一样)。根据您的用例,您可能不需要副本;您可能只需在idx
上迭代并对idx
中的所有i
使用x.slice(s![.., i])
即可。
https://stackoverflow.com/questions/52830679
复制相似问题