Python:Numpy—reshape、transpose、flatten

reshape

不改变原数据情况下修改形状且创造一个新的np数组

numpy.reshape(a, newshape, order=‘C’)

a:要修改形状的数组
newshape:整数或者整数数组,新的形状应当兼容原有形状
order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。

a=[1,2,3,4,5,6]
b=np.reshape(a, (2,3),'C')
c=np.reshape(a, (2,3),'F')
print(a)
print(b)
print(c)

>>>
[1, 2, 3, 4, 5, 6]
[[1 2 3]
 [4 5 6]]  # 按行读下来是123456
[[1 3 5]
 [2 4 6]]  # 按列读下来是123456

ndarray调用

ndarray:N 维数组对象 ndarray,下面的np.array(a)就是将a化为ndarray

ndarray.reshape(d1,d2…)

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

transpose

对换数组的维度,倒置

ndarray.T
ndarray.transpose

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


>>>
[[1, 2, 3], [4, 5, 6]]
[[1 4]
 [2 5]
 [3 6]]
[[1 4]
 [2 5]
 [3 6]]

flatten

不改变原数据情况下修改为1维且创造一个新的np数组

ndarray.flatten(order=‘C’)

order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘K’ – 元素在内存中的出现顺序

a=[[1,2,3],
   [4,5,6]]
b=np.array(a).flatten('C')
c=np.array(a).flatten('F')
print(a)
print(b)
print(c)


>>>
[[1, 2, 3], [4, 5, 6]]
[1 2 3 4 5 6]
[1 4 2 5 3 6]
发布了178 篇原创文章 · 获赞 140 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42146775/article/details/104596891