numpy.array变形记

2020年7月9日 / 12次阅读 / Last Modified 2020年7月10日
NumPy

对于numpy.array(ndarray),我们有好几种方法和改变它的shape。

reshape函数

>>> a = np.arange(100)
>>> a.shape
(100,)
>>> id(a)
3061151528
>>> a = a.reshape(5,20)
>>> a.shape
(5, 20)
>>> id(a)
3040477536

reshape用的比较多,它会重新生产一个ndarray对象。

如果对reshape函数输入-1,可实现自动计算维度长度的功能:

>>> a.shape
(2, 5, 2, 5)
>>> a.reshape(4,-1).shape
(4, 25)
>>> a.reshape(5,-1).shape
(5, 20)

在看一个 -1 的情况:

a = np.arange(30)
>>> b = a.reshape((2, -1, 3))  # -1 means "whatever is needed"
>>> b.shape
(2, 5, 3)
>>> b
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11],
        [12, 13, 14]],

       [[15, 16, 17],
        [18, 19, 20],
        [21, 22, 23],
        [24, 25, 26],
        [27, 28, 29]]])

resize函数

与reshape不同的是,resize就地变形,不会生产新的ndarray对象。

>>> a.shape
(5, 20)
>>> id(a)
3040477536
>>> a.resize(20,5)
>>> a.shape
(20, 5)
>>> id(a)
3040477536

T转置(transpose()函数)

还记得线性代数里的矩阵转置嘛。。。

>>> a.shape
(20, 5)
>>> a.T.shape
(5, 20)
>>> id(a)
3040477536
>>> a = a.T
>>> id(a)
3040477576

使用transpose()函数,也是一样的。

ravel函数

降维打击

>>> a = np.arange(100).reshape(2,5,2,5)
>>> a.shape
(2, 5, 2, 5)
>>> a.ravel().shape
(100,)

遍历ndarray中,也有介绍ravel函数。以下是关于ravel出来的一维数组数据的顺序说明:

The order of the elements in the array resulting from ravel() is normally “C-style”, that is, the rightmost index “changes the fastest”, so the element after a[0,0] is a[0,1]. If the array is reshaped to some other shape, again the array is treated as “C-style”.

np.newaxis和np.expand_dims

np.newaxis和np.expand_dims都可以用来增加ndarray的维度,用法如下:

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)
>>>
>>> a[np.newaxis,:]
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis,:].shape
(1, 10)
>>> a[np.newaxis,:,np.newaxis].shape
(1, 10, 1)
>>>
>>> b = a.reshape(2,5)
>>> b.shape
(2, 5)
>>> np.expand_dims(b, axis=0).shape
(1, 2, 5)
>>> np.expand_dims(b, axis=1).shape
(2, 1, 5)
>>> np.expand_dims(b, axis=2).shape
(2, 5, 1)

-- EOF --

本文链接:https://www.pynote.net/archives/2210

留言区

电子邮件地址不会被公开。 必填项已用*标注


前一篇:
后一篇:

More


©Copyright 麦新杰 Since 2019 Python笔记

go to top