Numpy 修改数组维度

numpy中数组维度属性

broadcast : 产生模仿广播的对象
broadcast_to : 将数组广播到新形状
expand_dims : 扩展数组的形状
squeeze : 从数组的形状中删除一维条目

numpy.broadcast

numpy.broadcast 用于模仿广播的对象,它返回一个对象,该对象封装了将一个数组广播到另一个数组的结果。

该函数使用两个数组作为输入参数,如下实例:

实例

import numpy as np
 
x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])  
 
# 对 y 广播 x
b = np.broadcast(x,y)  
# 它拥有 iterator 属性,基于自身组件的迭代器元组
 
print ('对 y 广播 x:')
r,c = b.iters
 
# Python3.x 为 next(context) ,Python2.x 为 context.next()
print (next(r), next(c))
print (next(r), next(c))
print ('\n')
# shape 属性返回广播对象的形状
 
print ('广播对象的形状:')
print (b.shape)
print ('\n')
# 手动使用 broadcast 将 x 与 y 相加
b = np.broadcast(x,y)
c = np.empty(b.shape)
 
print ('手动使用 broadcast 将 x 与 y 相加:')
print (c.shape)
print ('\n')
c.flat = [u + v for (u,v) in b]
 
print ('调用 flat 函数:')
print (c)
print ('\n')
# 获得了和 NumPy 内建的广播支持相同的结果
 
print ('x 与 y 的和:')
print (x + y)
输出结果为:

对 y 广播 x:
1 4
1 5


广播对象的形状:
(3, 3)


手动使用 broadcast 将 x 与 y 相加:
(3, 3)


调用 flat 函数:
[[5. 6. 7.]
 [6. 7. 8.]
 [7. 8. 9.]]


x 与 y 的和:
[[5 6 7]
 [6 7 8]
 [7 8 9]]

numpy.broadcast_to

numpy.broadcast_to 函数将数组广播到新形状。它在原始数组上返回只读视图。 它通常不连续。 如果新形状不符合 NumPy 的广播规则,该函数可能会抛出ValueError。

numpy.broadcast_to(array, shape, subok)

实例

import numpy as np
 
a = np.arange(4).reshape(1,4)
 
print ('原数组:')
print (a)
print ('\n')
 
print ('调用 broadcast_to 函数之后:')
print (np.broadcast_to(a,(4,4)))
输出结果为:

原数组:
[[0 1 2 3]]


调用 broadcast_to 函数之后:
[[0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]]

numpy.expand_dims

numpy.expand_dims 函数通过在指定位置插入新的轴来扩展数组形状,函数格式如下:

 numpy.expand_dims(arr, axis)

参数说明:

  • arr:输入数组
  • axis:新轴插入的位置

实例

import numpy as np
 
x = np.array(([1,2],[3,4]))
 
print ('数组 x:')
print (x)
print ('\n')
y = np.expand_dims(x, axis = 0)
 
print ('数组 y:')
print (y)
print ('\n')
 
print ('数组 x 和 y 的形状:')
print (x.shape, y.shape)
print ('\n')
# 在位置 1 插入轴
y = np.expand_dims(x, axis = 1)
 
print ('在位置 1 插入轴之后的数组 y:')
print (y)
print ('\n')
 
print ('x.ndim 和 y.ndim:')
print (x.ndim,y.ndim)
print ('\n')
 
print ('x.shape 和 y.shape:')
print (x.shape, y.shape)
输出结果为:

数组 x:
[[1 2]
 [3 4]]


数组 y:
[[[1 2]
  [3 4]]]


数组 x 和 y 的形状:
(2, 2) (1, 2, 2)


在位置 1 插入轴之后的数组 y:
[[[1 2]]

 [[3 4]]]


x.ndim 和 y.ndim:
2 3


x.shape 和 y.shape:
(2, 2) (2, 1, 2)

numpy.squeeze

numpy.squeeze 函数从给定数组的形状中删除一维的条目,函数格式如下:

numpy.squeeze(arr, axis)

参数说明:

  • arr:输入数组
  • axis:整数或整数元组,用于选择形状中一维条目的子集

实例

import numpy as np
 
x = np.arange(9).reshape(1,3,3)
 
print ('数组 x:')
print (x)
print ('\n')
y = np.squeeze(x)
 
print ('数组 y:')
print (y)
print ('\n')
 
print ('数组 x 和 y 的形状:')
print (x.shape, y.shape)
输出结果为:

数组 x:
[[[0 1 2]
  [3 4 5]
  [6 7 8]]]


数组 y:
[[0 1 2]
 [3 4 5]
 [6 7 8]]


数组 x 和 y 的形状:
(1, 3, 3) (3, 3)