可以使用.重塑(-1)将2D数组重新塑造为1D数组。 例如:

>>> a = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> a.reshape(-1)
array([[1, 2, 3, 4, 5, 6, 7, 8]])

通常,array[-1]表示最后一个元素。 这里-1是什么意思?


当前回答

转换的最终结果是最终数组中的元素数量与初始数组或数据帧的元素数量相同。

-1对应行或列的未知计数。 我们可以把它看成x(未知)X是用原始数组中的元素数除以-1的有序对的另一个值得到的。

例子:

12个元素与重塑(-1,1)对应的数组x=12/1=12行1列。


12个元素具有重塑(1,-1)对应于一个有1行和x=12/1=12列的数组。

其他回答

根据文档:

Newshape: int或int的元组 新形状应与原形状兼容。如果一个 整数,则结果将是该长度的一维数组。一个形状 维度可以是-1。在本例中,该值是从 数组的长度和剩余维度。

"在所有其他维度都已指定的情况下,推断出这个维度"

显式地,这将使-1维度成为原始数组的维度积与新指定的dim的维度积的商。如果不是整数,则返回错误。

例如,对于一个形状数组(2,3,5),以下都是等价的:

a = np.random.rand(2, 3, 5)

np.reshape(a, (-1,  2,  5))
np.reshape(a, ( 3, -1,  5))
np.reshape(a, ( 3,  2, -1))

这仅仅意味着您不确定您可以给出多少行或列,并且您要求numpy建议重新塑造的列或行数。

Numpy提供了-1的最后一个示例 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

检查下面的代码及其输出,以更好地理解关于(-1):

代码:

import numpy
a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
print("Without reshaping  -> ")
print(a)
b = numpy.reshape(a, -1)
print("HERE We don't know about what number we should give to row/col")
print("Reshaping as (a,-1)")
print(b)
c = numpy.reshape(a, (-1,2))
print("HERE We just know about number of columns")
print("Reshaping as (a,(-1,2))")
print(c)
d = numpy.reshape(a, (2,-1))
print("HERE We just know about number of rows")
print("Reshaping as (a,(2,-1))")
print(d)

输出:

Without reshaping  -> 
[[1 2 3 4]
 [5 6 7 8]]
HERE We don't know about what number we should give to row/col
Reshaping as (a,-1)
[[1 2 3 4 5 6 7 8]]
HERE We just know about number of columns
Reshaping as (a,(-1,2))
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
HERE We just know about number of rows
Reshaping as (a,(2,-1))
[[1 2 3 4]
 [5 6 7 8]]

长话短说:您设置一些维度,让NumPy设置其余的维度。

(userDim1, userDim2, ..., -1) -->>

(userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))
numpy.reshape(a,newshape,order{})

查看下面的链接获取更多信息。 https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

对于下面的示例,您提到的输出将结果向量解释为单行。(-1)表示行数为1。 如果

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
b = numpy.reshape(a, -1)

输出:

matrix([[1, 2, 3, 4, 5, 6, 7, 8]])

这可以用另一个例子来更准确地解释:

b = np.arange(10).reshape((-1,1))

输出:(1维柱状阵列)

array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

or

b = np.arange(10).reshape((1,-1))

输出:(是一个1维行数组)

array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])