Python多维符号自动转置

标签 python numpy

我有以下最小示例:

a = np.zeros((5,5,5))
a[1,1,:] = [1,1,1,1,1]
print(a[1,:,range(4)])

我希望输出一个 5 行 4 列的数组,其中我们在第二行有一个。相反,它是一个具有 4 行和 5 列的数组,其中一个在第二列。这里发生了什么,我该怎么做才能获得预期的输出?

最佳答案

这是混合基本索引和高级索引的示例,如 https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing 中所述。

切片维度已附加到末尾。

对于一个标量索引,这是此处描述的歧义的边缘情况。它已在之前的 SO 问题和一个或多个错误/问题中进行了讨论。

Numpy sub-array assignment with advanced, mixed indexing

在这种情况下,您可以用切片替换范围,并获得预期的顺序:

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多维符号自动转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45471197/

相关文章:

python - Numpy:数组 > 5 产生 "The truth value of an array with more than one element is ambiguous"

python - 并行填充 numpy 数组?

python - 使用唯一值列表 reshape pandas 数据框

python - 搜索一个数组中的特定元素并复制另一数组中的整个相应行

python - 是否有一个简单的 DataFrame 方法可以根据另一行中另一列中的值逐行复制列中的值?

python - 邮件确认错误 rest-auth

python - 为 Pandas Dataframe 中的重复集创建规则

python - 在 f.read 上过滤多个字符串

python - 只读对象模型的 SqlAlchemy 优化

python - 如何使用 scipy 稀疏矩阵 column_stack 一个 numpy 数组?