[英]Slicing using arrays/indices
I am trying to iteratively access an numpy array using indices and arrays. 我正在尝试使用索引和数组迭代访问numpy数组。 The following example pretty much sums up my problem:
以下示例几乎总结了我的问题:
x = np.arange(12)
x.shape = (3,2,2)
nspace = np.array([[0,0], [0,1], [1,0], [1,1]])
for it in range(len(nspace)):
x[:,nspace(it)] = np.array([1,1,1])
If things worked the way I am thinking, the code would print 4 separate arrays: 如果事情按照我的想法工作,则代码将打印4个单独的数组:
[0,4,8]
[1,5,9]
[2,6,10]
[3,7,11]
But I get an error. 但是我得到一个错误。 I understand the my indexing is wrong, but I cannot figure out how to get the result I want.
我知道我的索引是错误的,但是我无法弄清楚如何获得想要的结果。
It is important that everything happens within a loop because I want to be able to change the dimensions of x. 所有事情都发生在循环中很重要,因为我希望能够更改x的尺寸。
EDIT0: I need a general solution that does require. EDIT0:我需要一个确实需要的常规解决方案。 me to write: space[0,0], space[0,1], etc.
我要写:space [0,0],space [0,1]等。
EDIT1: I changed the print to an assignment operation because what actually need is to assign the result of a function that I call inside the loop. EDIT1:我将打印更改为赋值操作,因为实际需要的是赋值我在循环内调用的函数的结果。
EDIT2: I did not include the Traceback because I doubt it will be useful. EDIT2:我没有包括Traceback,因为我怀疑它会有用。 Anyway, here it is:
无论如何,这里是:
Traceback (most recent call last):
File "<ipython-input-600-50905b8b5c4d>", line 5, in <module>
print(x[:,nspace(it)])
TypeError: 'numpy.ndarray' object is not callable
You don't need to use the for
loop. 您不需要使用
for
循环。 Use reshape
and transpose
. 使用
reshape
和transpose
。
x.reshape(3, 4).T
Gives: 得到:
array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
If you wanted to iterate the result: 如果要迭代结果:
for row in x.reshape(3, 4).T:
print(row)
You get the error, because you should have square brackets for element access on the last line. 您会收到此错误,因为在最后一行上应该有方括号用于元素访问。
import numpy as np
x = np.arange(12)
x.shape = (3,2,2)
nspace = np.array([[0,0], [0,1], [1,0], [1,1]])
for it in range(len(nspace)):
print(x[:,nspace[it]])
EDIT: 编辑:
And one possible solution to get your expected result: 一种可能的解决方案来获得预期的结果:
import numpy as np
x = np.arange(12)
x.shape = (3,2,2)
nspace = np.array([[0,0], [0,1], [1,0], [1,1]])
y = x.flatten()
for i in range(x.size//x.shape[0]):
print y[i::4]
You need to provide the first and the second index and use []
brackets instead of ()
to access the array elements. 您需要提供第一个索引和第二个索引,并使用
[]
括号而不是()
来访问数组元素。
import numpy as np
x = np.arange(12)
x.shape = (3,2,2)
for it in range(len(nspace)):
print(x[:,nspace[it][0], nspace[it][1]])
Output 产量
[0 4 8]
[1 5 9]
[ 2 6 10]
[ 3 7 11]
You can also use reshape
directly as 您也可以直接使用
reshape
作为
x = np.arange(12).reshape(3,2,2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.