Python 之NumPy
>>> 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)
>>> a.ravel() #扁平话处理,及只有一个维度
array([ 2.,8.,0.,6.,4.,5.,1.,1.,8.,9.,3.,6.])
>>> a.reshape(6,2) #改变形状为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 = np.floor(10*np.random.random((2,2)))
>>> a
array([[ 8.,8.], [ 0.,0.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[ 1.,8.], [ 0.,4.]])
>>> np.vstack((a,b)) #纵向合并
array([[ 8.,8.], [ 0.,0.], [ 1.,8.], [ 0.,4.]])
>>> np.hstack((a,b)) #横向合并
array([[ 8.,8.,1.,8.], [ 0.,0.,0.,4.]])
column_stack合并数组,值合并第一维度
>>> from numpy import newaxis
>>> np.column_stack((a,b)) # With 2D arrays
array([[ 8.,8.,1.,8.], [ 0.,0.,0.,4.]])
>>> a = np.array()
>>> b = np.array()
>>> a[:,newaxis]# This allows to have a 2D columns vector
array([[ 4.], [ 2.]])
>>> np.column_stack((a[:,newaxis],b[:,newaxis])) #合并2维数组
array([[ 4.,2.], [ 2.,8.]])
>>> np.vstack((a[:,newaxis],b[:,newaxis]))
array([[ 4.],
[ 2.],
[ 2.],
[ 8.]])
hsplit水平方向切割数组
>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ 9.,5.,6.,3.,6.,8.,0.,7.,9.,7.,2.,7.],
[ 1.,4.,9.,2.,2.,1.,0.,6.,2.,2.,4.,0.]])
>>> np.hsplit(a,3) # Split a into 3 切割成3个数组
,
[ 1.,4.,9.,2.]]),
array([[ 6.,8.,0.,7.],
[ 2.,1.,0.,6.]]),
array([[ 9.,7.,2.,7.],
[ 2.,2.,4.,0.]])]
array_split可以自定义切割的水平方向哈市垂直方向
>>> x = np.arange(8.0)
>>> np.array_split(x, 3) #array_split(ary, indices_or_sections, axis=0)
), array([ 3.,4.,5.]), array([ 6.,7.])]
复制
简单的赋值,b指向a的对象
>>> a = np.arange(12)
>>> b = a # no new object is created
>>> b is a # a and b are two names for the same ndarray object
True
>>> b.shape = 3,4 # changes the shape of a
>>> a.shape
(3, 4)
快照模式
>>> c = a.view()
>>> c is a
False
>>> c.base is a # c is a view of the data owned by a
True
>>> c.flags.owndata
False
>>> c.shape = 2,6 # a's shape doesn't change
>>> a.shape(3, 4)
>>> c = 1234 # a's data changes
>>> a
array([[ 0, 1, 2, 3],
,
[ 8, 9, 10, 11]])
深度拷贝
>>> d = a.copy() # a new array object with new data is created
>>> d is a
False
>>> d.base is a # d doesn't share anything with a
False
>>> d = 9999
>>> a
array([[ 0, 10, 10, 3],
,
[ 8, 10, 10, 11]])
页:
[1]