[英]numpy arrays slicing using reshape
I was learning how to reshape an array.我正在学习如何重塑数组。 I found several tutorials on the topic.我找到了几个关于这个主题的教程。 I have confusion after reading all those stuff.读完所有这些东西后,我感到困惑。
Suppose I declared an array using numpy假设我使用 numpy 声明了一个数组
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
I reshaped it我重新塑造了它
newarr = arr.reshape(4, 3)
The resultant array newarr
which has 4 rows and 3 columns结果数组newarr
有 4 行 3 列
I found another command for reshaping我找到了另一个重塑命令
arr.reshape(data.shape[d1],d2)
Here data is the array name d1 = dimension1 and d2= dimension2.这里的 data 是数组名 d1 = dimension1 和 d2= dimension2。
As per my knowledge, shape[0] returns numbers of rows of a 2-d array, shape[1] returns numbers of columns of a 2d array据我所知,shape[0] 返回二维数组的行数,shape[1] 返回二维数组的列数
if I write down如果我写下
newarr = arr.reshape(arr.shape[4],3)
I got an error tuple index out of range
.我得到一个错误tuple index out of range
。 Doesn't the previous command mean that create a 2d array with 4 rows and 3 columns?前面的命令不是意味着创建一个 4 行 3 列的二维数组吗?
I also tried the same command for我也尝试了相同的命令
newarr = arr.reshape(arr.shape[0],1)
It works fine with 12 rows and one column, So does this mean shape[0] returns numbers of columns?它适用于 12 行和 1 列,这是否意味着 shape[0] 返回列数?
I read various tutorials on slicing an array but this is not clear to me.我阅读了有关切片数组的各种教程,但这对我来说并不清楚。
What happen with newarr = arr.reshape(arr.shape[4],3) command? newarr = arr.reshape(arr.shape[4],3) 命令会发生什么?
arr is unidimensional, then only arr.shape[0] is defined arr 是一维的,那么只定义了 arr.shape[0]
Try printing arr.shape尝试打印 arr.shape
I found another command for reshaping我找到了另一个重塑命令
arr.reshape(data.shape[d1],d2)
This is not correct, not in the general case anyway.这是不正确的,无论如何在一般情况下都不正确。 This command makes the first dimension of newarr
match the d1´th dimension of the array data
.此命令使newarr
的第一个维度与数组data
的第 d1 个维度匹配。
You should stick to你应该坚持
newarr = arr.reshape(d1, d2)
Your arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
is an 1D array, there arent any rows/columns.您的arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
是一维数组,没有任何行/列。 Its just array of elements with indexing.它只是带有索引的元素数组。 Your arr.shape
has only one dimension with 12 values (12,)
.您的arr.shape
只有一维,有 12 个值(12,)
。 so, when you call arr.shape[0]
it returns number of elements in the dimension and it is 12.因此,当您调用arr.shape[0]
时,它返回维度中的元素数,为 12。
So, finally you are asking an arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
to reshape to newarr = arr.reshape(arr.shape[4],3)
where arr.shape[4]
is out of bound.所以,最后你要求arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
重塑为newarr = arr.reshape(arr.shape[4],3)
其中arr.shape[4]
超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.