①append、concatnate以及stack都有一个 axis 参数,用于控制数组合并是按行还是按列。
②对于append和concatnate,待合并的数组必须有相同的行数或列数(满足一个即可)。
③stack、hstack、dstack待合并的数组必须具有相同的形状( shape)。 

一、更改数组的形状

reshape()和resize()方法都是修改向量额维度,但是reshape不对向量本身进行修改,resize改变向量的本身:

#coco
#数组的变形
import numpy as np
'''----------------------------------------reshape()-------------------------------------------------------------------'''
arr = np.arange(10)
print(arr)
# 将向量 arr 维度变换为2行5列
print(arr.reshape(2, 5))
# 指定维度时可以只指定行数或列数, 其他用 -1 代替,所指定的行数或列数一定要能被整除(如10不能被3整除)
print(arr.reshape(5, -1))
print(arr.reshape(-1, 5))
'''-----------------------------------------resize()------------------------------------------------------------------'''
arr = np.arange(10)
print(arr)
# 将向量 arr 维度变换为2行5列
arr.resize(2, 5)
print(arr)

.T

#转置操作
arr = np.arange(12).reshape(3, 4)
# 向量 arr 为3行4列
print(arr)
# 将向量 arr 进行转置为4行3列
print(arr.T)

ravel()对数组按照行或者列进行展开操作:

import numpy as np
arr = np.arange(6).reshape(2, -1)
print(arr)
# 按照列优先,展平
print("按照列优先,展平")
print(arr.ravel('F'))
# 按照行优先,展平
print("按照行优先,展平")
print(arr.ravel())
print('arr',arr)

 flatten() 也是对数组进行展开操作:

import numpy as np
#把矩阵转换为向量,这种需求经常出现在卷积网络与全连接层之间。
a =np.floor(10*np.random.random((3,4)))
print(a)
print(a.flatten())

ravel()和flatten()的区别:

        flatten产生一个副本,ravel不产生,ravel会对原始数据产生影响,flatten不会,大概意思就是使用了新的内存空间吧。

squeeze() 这是一个重要用来降维的函数,把矩阵中含1的维度去掉:

import numpy as np
arr = np.arange(3).reshape(3, 1)
print(arr)
print(arr.shape)  #数组的行列数 (3,1)
print(arr.squeeze().shape)  # (3,)
print(arr)
arr1 = np.arange(6).reshape(3, 1, 2, 1)
print(arr1)
print(arr1.shape)  # (3, 1, 2, 1)
print(arr1.squeeze().shape)  # (3, 2)
print(arr1)

 transpose()对高维矩阵进行轴对换,这个在深度学习中经常使用,比如把图片表示颜色的RGB顺序,改为GBR的顺序:

import numpy as np

arr2 = np.arange(24).reshape(2, 3, 4)
print(arr2.shape)  # (2, 3, 4)
print(arr2.transpose(1, 2, 0).shape)  # (3, 4, 2)

二、数组合并

(1)append()

#合并一维数组
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.append(a, b)
print(c)
# [1 2 3 4 5 6]

#合并多维数组
a = np.arange(4).reshape(2, 2)
print(a)
b = np.arange(4).reshape(2, 2)
print(b)
# 按行合并
c = np.append(a, b, axis=0)
print('按行合并后的结果')
print(c)
print('合并后数据维度', c.shape)
# 按列合并
d = np.append(a, b, axis=1)
print('按列合并后的结果')
print(d)
print('合并后数据维度', d.shape)

(2)concatenate() 沿指定轴连接数组或矩阵

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])

c = np.concatenate((a, b), axis=0)
print(c)
d = np.concatenate((a, b.T), axis=1)
print(d)

(3)stack()

沿指定轴堆叠数组或矩阵

import numpy as np

a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(np.stack((a, b), axis=0))

输出结果:

[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

Logo

更多推荐