[英]How to reshape this numpy array to exclude the “extra dimension”?
I have a numpy array arr1
which it an output of a function. 我有一个numpy数组
arr1
,它是函数的输出。 The array has an "extra" dimension caused by each element inside the numpy array being cast as a numpy array itself. 该数组具有“额外”维度,这是由于numpy数组中的每个元素本身都被强制转换为numpy数组所致。
arr1.shape
outputs (100, 20, 1)
arr1.shape
输出(100, 20, 1)
arr1.shape
(100, 20, 1)
If I print the array, print(arr1[0])
outputs 如果我打印数组,则
print(arr1[0])
输出
array([[-212537.61715316],
[ 7258.38476409],
[ 37051.91250884],
[-146278.00512207],
[-185792.24620168],
[-200794.59538468],
[-195981.27879612],
[-177912.26034464],
[-152212.805867 ],
[-118873.26452198],
[ -64657.64682999],
[ 306884.11196766],
[-191073.9891907 ],
[-104992.44840277],
[ -67834.43041102],
[ -21810.77063542],
[ 17307.24511071],
[ 55607.49775471],
[ 91259.82533592],
[ 119207.40589797]])
If I reshape with arr1.reshape((100,20))
, I get the following output for print(arr1.reshape((100,20))[0])
: 如果我使用
arr1.reshape((100,20))
重塑, arr1.reshape((100,20))
得到以下print(arr1.reshape((100,20))[0])
:
array([-212537.61715316, 7258.38476409, 37051.91250884,
-146278.00512207, -185792.24620168, -200794.59538468,
-195981.27879612, -177912.26034464, -152212.805867 ,
-118873.26452198, -64657.64682999, 306884.11196766,
-191073.9891907 , -104992.44840277, -67834.43041102,
-21810.77063542, 17307.24511071, 55607.49775471,
91259.82533592, 119207.40589797])
My question is: how do I exclude this "extra" one, but retain the original shape of the array arr1
? 我的问题是:如何排除此“额外”对象,但保留数组
arr1
的原始形状?
Is the best method to use .reshape()
? 是使用
.reshape()
的最佳方法吗? If not, what is the best way to do this? 如果没有,什么是最好的方法?
You might be looking for numpy.squeeze
: 您可能正在寻找
numpy.squeeze
:
http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.squeeze.html http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.squeeze.html
a = np.arange(10*20).reshape((10, 20, 1))
print(a.shape)
# (10, 20, 1)
a = a.squeeze()
print(a.shape)
# (10, 20)
Note the other answer since your reshape
should have worked you were just looking at the output incorrectly. 请注意其他答案,因为您的
reshape
应该可以正常工作,而您只是错误地查看了输出。
You are using reshape
correctly. 您正在正确使用
reshape
。
arr2 = arr1.reshape((100,20))
The shape of this will be (100,20), the same as arr1
without the last dimension. 其形状将为(100,20),与没有最后尺寸的
arr1
相同。
arr1[0]
has shape (20,1), and thus prints as a column. arr1[0]
形状为(20,1),因此打印为一列。
arr2[0]
has shape (20,), and thus prints as a row(s) (count the brackets). arr2[0]
形状为(20,),因此打印为一行(计数括号)。 You might not like the display, but the shape is correct. 您可能不喜欢显示器,但是形状正确。
squeeze
can also be used to take out the extra dimension, but the results will be same. squeeze
也可以用来去除多余的尺寸,但结果将相同。
print(arr2[0][:,None])
should print as a column. print(arr2[0][:,None])
应该打印为一列。 It effectively adds that extra dimension back on prior to printing. 它可以在打印之前有效地增加额外的尺寸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.