Python多维符号自动转置 [英] Python multi-dimensional notation transpose automatically
问题描述
我有以下最小示例:
a = np.zeros((5,5,5))
a[1,1,:] = [1,1,1,1,1]
print(a[1,:,range(4)])
我希望输出5行4列的数组,而第二行有1列.相反,它是一个具有4行5列且第二列具有1的数组.这里发生了什么,我该怎么做才能获得预期的输出?
I would expect as output an array with 5 rows and 4 columns, where we have ones on the second row. Instead it is an array with 4 rows and 5 columns with ones on the second column. What is happening here, and what can I do to get the output I expected?
推荐答案
This is an example of mixed basic and advanced indexing, as discussed in https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing
切片尺寸已附加到末尾.
The slice dimension has been appended to the end.
使用一个标量索引,对于此处描述的歧义,这是一个边际情况.之前的SO问题和一个或多个Bug/问题中都对此进行了讨论.
With one scalar index this is a marginal case for the ambiguity described there. It's been discussed in previous SO questions and one or more bug/issues.
在这种情况下,您可以用切片替换范围,并获得预期的顺序:
In this case you can replace the range with a slice, and get the expected order:
In [215]: a[1,:,range(4)].shape
Out[215]: (4, 5) # slice dimension last
In [216]: a[1,:,:4].shape
Out[216]: (5, 4)
In [219]: a[1][:,[0,1,3]].shape
Out[219]: (5, 3)
这篇关于Python多维符号自动转置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!