问题描述
numpy中np.reshape()
和np.newaxis
都能增加array
的维度,两者有何区别?
import numpy as np
a = np.ones(12)
b = a.reshape(-1, 1)
c = a.reshape(-1, 1, 1)
d = a[:, np.newaxis]
e = a[:, np.newaxis, np.newaxis]
print(a.shape) # (12,)
print(b.shape) # (12, 1)
print(c.shape) # (12, 1, 1)
print(d.shape) # (12, 1)
print(e.shape) # (12, 1, 1)
异同
两者没有特别大的区别。两者都创建一个view,使用与原始data使用相同的缓冲区。
print(a.__array_interface__)
print(b.__array_interface__)
print(d.__array_interface__)
"""
{'data': (2012817932320, False), 'strides': None, 'descr': [('', '<f8')], 'typestr': '<f8', 'shape': (12,), 'version': 3}
{'data': (2012817932320, False), 'strides': None, 'descr': [('', '<f8')], 'typestr': '<f8', 'shape': (12, 1), 'version': 3}
{'data': (2012817932320, False), 'strides': None, 'descr': [('', '<f8')], 'typestr': '<f8', 'shape': (12, 1), 'version': 3}
"""
但是在使用时有一个小区别:当要操作多个未知维度时,使用numpy.newaxis
而不是ndarray.reshape()
。
例如:
import numpy as np
a = np.ones((3, 3))
b = a[:, np.newaxis, :]
print(b.shape) # (3, 1, 3)
c = a.reshape(-1, 1, -1) # ValueError: can only specify one unknown dimension