把一个数组转化为指定的形状(改变维度)
import numpy as np
a = np.array([1,2,3,4,5, 6])
print(a.ndim) # 输出维度 1
b = a.reshape(2,3)
# 输出b的维度
print(b.ndim) # 输出维度 2
返回一个迭代器,循环输出数组的每一个元素(以一维的状态输出)
import numpy as np
a = np.array([1, 2, 3], [4, 5, 6])
for i in a.flat:
print(i, end=' ')
# 输出 1 2 3 4 5 6
将数组的维度值进行对换,比如二维数组维度(2,4)使用该方法后为(4,2)
import numpy as np
array_one = np.arange(12).reshape(3, 4)
print("原数组:")
print(array_one)
print("使用transpose()函数后的数组:")
print(np.transpose(array_one))
原数组:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
使用transpose()函数后的数组:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
与transpose方法效果一样
import numpy as np
array_one = np.arange(12).reshape(3, 4)
print("使用T属性后的数组:")
print(array_one.T)
使用T属性后的数组:
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
参数1:输入数组 参数2:axis=新轴插入的位置
在指定位置插入新的轴,从而扩展数组的维度
0是横向,1是纵向
示例
import numpy as np
# 创建一个一维数组
a = np.array([1, 2, 3])
print(a.shape) # 输出: (3,)
# 在第 0 维插入新维度
b = np.expand_dims(a, axis=0)
print(b)
# 输出:
# [[1 2 3]]
print(b.shape) # 输出: (1, 3)
# 在第 1 维插入新维度
c = np.expand_dims(a, axis=1)
print(c)
# 输出:
# [[1]
# [2]
# [3]]
print(c.shape) # 输出: (3, 1)
import numpy as np
# 创建一个数组
c = np.array([[[1, 2, 3]]])
print(c.shape) # 输出: (1, 1, 3)
# 移除第 0 维
d = np.squeeze(c, axis=0)
print(d)
# 输出:
# [[1 2 3]]
print(d.shape) # 输出: (1, 3)
# 移除第 1 维
e = np.squeeze(c, axis=1)
print(e)
# 输出:
# [[1 2 3]]
print(e.shape) # 输出: (1, 3)
# 移除第 2 维
f = np.squeeze(c, axis=2)
print(f)
# 输出:
# ValueError: cannot select an axis to squeeze out which has size not equal to one
vstack() 和 hstack() 要求堆叠的数组在某些维度上具有相同的形状。如果维度不一致,将无法执行堆叠操作。
import numpy as np
# 创建两个形状不同的数组,行数一致
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5], [6]])
print(arr1.shape) # (2, 2)
print(arr2.shape) # (2, 1)
# 使用 hstack 水平堆叠数组
result = np.hstack((arr1, arr2))
print(result)
# 输出:
# [[1 2 5]
# [3 4 6]]
# 创建两个一维数组
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# 使用 vstack 垂直堆叠数组
result = np.vstack((arr1, arr2))
print(result)
# 输出:
# [[1 2 3]
# [4 5 6]]