numpy中轴处理的实现
numpy中轴参数的意义
指定的轴是被压缩的轴
沿轴的时候可以指定两个轴,即面被压缩,以面作为输入
numpy中轴转动
numpy中添加新轴
np.newaxis 在使用和功能上等价于 None,其实就是 None 的一个别名
import numpy as np
a=np.array([1,2,3])
b=a[np.newaxis,:]
c=a[:,np.newaxis]
numpy中轴扩展
numpy.expand_dims(a,axis)
扩展一个维就是把一个维往后挪,或者增加
Numpy中广播数据维
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.shape)
print(a)
print()
b = np.broadcast_to(a, (4, 4))
print(">>>")
print(b.shape)
print(b)
>>>
(1, 4)
[[0 1 2 3]]
>>>
(4, 4)
[[0 1 2 3]
[0 1 2 3]
[0 1 2 3]
[0 1 2 3]]
numpy中缩减轴
numpy交换两个轴
numpy.swapaxes(arr,axis1, axis2)
其中:
- arr:要交换其轴的输入数组
- axis1:对应第一个轴的整数
- axis2:对应第二个轴的整数
numpy滚动轴
numpy.rollaxis()函数向后滚动特定的轴,直到一个特定位置。这个函数接受三个参数:
numpy.rollaxis(arr,axis, start)
其中:
- arr:输入数组
- axis:要向后滚动的轴,其它轴的相对位置不会改变
- start:默认为零,表示完整的滚动。会滚动到特定位置。
a = np.arange(24).reshape(2, 3, 4)
print(">>>")
print(a.shape)
print(a)
print()
roll = np.rollaxis(a, 2) # 把第2个轴滚动到0维位置
print(">>>")
print(roll.shape)
print(roll)
print()
roll2 = np.rollaxis(a, 2, 1) # 把第2个轴滚动到1维位置
print(">>>")
print(roll2.shape)
print(roll2)
print()
>>>
(2, 3, 4)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
>>>
(4, 2, 3)
[[[ 0 4 8]
[12 16 20]]
[[ 1 5 9]
[13 17 21]]
[[ 2 6 10]
[14 18 22]]
[[ 3 7 11]
[15 19 23]]]
>>>
(2, 4, 3)
[[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]]
[[12 16 20]
[13 17 21]
[14 18 22]
[15 19 23]]]
numpy中数据拼接操作concatenate
concatenate:沿现有轴加入一系列数组
stack:沿新轴加入一系列数组,即stack(arrays, axis=0)
column_stack:把1维数组当作列堆叠成二维数组
为了向后兼容
dstack:沿深度方向堆叠数组
hstack:沿水平方法堆叠数组
vstack:沿垂直方向堆叠数组
相关文章