[英]How to rearrange columns in an ndarray in numpy
I stumbled upon what I think is a weird (or at least unintuitive) behavior of numpy and I would like to understand why it behaves that way.我偶然发现了我认为 numpy 的奇怪(或至少不直观)行为,我想了解它为什么会这样。 Let's generate a generic array of shape (4, 3, 3).让我们生成一个形状为 (4, 3, 3) 的通用数组。
import numpy as np
arr = np.arange(4*3*3).reshape((4, 3, 3))
Thinking about arr as a list of four three-by-three matrices I want to now swap the first two columns of the first matrix in the list.将 arr 视为四个 3×3 矩阵的列表,我现在想交换列表中第一个矩阵的前两列。 I can just reorder the columns with an index list:我可以使用索引列表重新排序列:
idx = np.array([1, 0, 2])
m = arr[0]
m[:, idx]
>>> array([[1, 0, 2],
[4, 3, 5],
[7, 6, 8]])
I see that i successfully swapped the two columns.我看到我成功交换了两列。 However, if I do try to do same directly with arr, I get:但是,如果我尝试直接用 arr 做同样的事情,我会得到:
arr[0, :, idx]
>>> array([[1, 4, 7],
[0, 3, 6],
[2, 5, 8]])
I guess I'm doing something wrong but I don't understand this behavior.我想我做错了什么,但我不明白这种行为。
This weird output is because when you are doing这个奇怪的 output 是因为当你在做
m = arr[0]
m[:, idx]
then m becomes a whole different "array" with data of "arr" but when you are doing arr[0, :, arr]
there arr is a list which has arrays然后 m 变成一个完全不同的“数组”,数据为“arr”,但是当你在做arr[0, :, arr]
时, arr 是一个列表,其中包含 arrays
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.