形状变换

阅读: 6043     评论:0

前面我们介绍过,可以通过数组的shape属性,查看它的形状:

>>> a = np.floor(10*np.random.random((3,4)))
>>> a
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])
>>> a.shape
(3, 4)

上面的例子中,先通过numpy的random函数生成一个随机3行4列数组,再对每个元素乘10,最后用floor函数取整。

有很多数组方法可以变换它的形状,并且不修改原始数组本身:

>>> a.ravel()  # 平铺数组成为一维数组
array([ 2.,  8.,  0.,  6.,  4.,  5.,  1.,  1.,  8.,  9.,  3.,  6.])
>>> a.reshape(6,2)  # 调整形状
array([[ 2.,  8.],
       [ 0.,  6.],
       [ 4.,  5.],
       [ 1.,  1.],
       [ 8.,  9.],
       [ 3.,  6.]])
>>> a.T  # 返回转置数组
array([[ 2.,  4.,  8.],
       [ 8.,  5.,  9.],
       [ 0.,  1.,  3.],
       [ 6.,  1.,  6.]])
>>> a.T.shape
(4, 3)
>>> a.shape
(3, 4)

reshape方法不会修改数组本身,resize则正好相反:

>>> a
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])
>>> a.resize((2,6))
>>> a
array([[ 2.,  8.,  0.,  6.,  4.,  5.],
       [ 1.,  1.,  8.,  9.,  3.,  6.]])
>>> a.resize((2,7)) # 突发奇想,作死试试
alueError                                Traceback (most recent call last)
<ipython-input-162-8df1a3f67bca> in <module>()
----> 1 a.resize(2,7)

ValueError: cannot resize an array that references or is referenced
by another array in this way.  Use the resize function

>>> np.resize(a, (2,7)) # 但是...居然可以这么干!
array([[2., 8., 0., 6., 4., 5., 1.],
       [1., 8., 9., 3., 6., 2., 8.]])

# 再次提醒,在numpy中有各种类似的坑,你根本踩不过来,所以不要尝试一些自己不确定的东西。

如果reshape方法的一个参数是-1,那么这个参数的实际值会自动计算得出:

>>> a.reshape(3,-1)
array([[ 2.,  8.,  0.,  6.],
       [ 4.,  5.,  1.,  1.],
       [ 8.,  9.,  3.,  6.]])

更多内容参考:ndarray.shape, reshape, resize, ravel


 添加删除去重 堆积数组 

评论总数: 0


点击登录后方可评论