从变量中进行 Numpy 切片 [英] Numpy slicing from variable
本文介绍了从变量中进行 Numpy 切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用在变量中预定义的切片对 numpy 数组进行切片.这有效:
I'm trying to slice a numpy array using a slice that is predefined in a variable. This works:
b = fromfunction(lambda x,y: 10*x+y, (5,4),dtype=int) # Just some matrix
b[1:3,1:3]
# Output:
# array([[11, 12],
# [21, 22]])
但我想做的是这样的事情:
But what I want to do is somthing like this:
slice = "1:3,1:3"
b[slice]
# Output:
# array([[11, 12],
# [21, 22]])
切片变量的类型对我来说并不重要,我只是以字符串为例.如何保存这样的切片说明符?
It is not important to me what type the slice-variable has, I'm just using a string as an example. How do I save a slice-specifier like that?
推荐答案
可以使用内置的slice
函数
s = slice(1,3)
b[s,s]
ds = (s,s)
b[ds]
这篇关于从变量中进行 Numpy 切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文