numpy学习专题
十二、numpy修改数组维度
修改数组维度
1.broadcast() 用于模仿广播对象,它返回一个对象,对象中封装了将一个数组广播到另一个数组的结果
import numpy as np
x = np. array( [ [ 1 ] , [ 2 ] , [ 4 ] ] )
y = np. array( [ 4 , 5 , 6 ] )
print ( x)
print ( y)
b = np. broadcast( x, y)
print ( b)
r, c = b. iters
print ( r)
print ( c)
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
print ( next ( r) , next ( c) )
b = np. broadcast( x, y)
print ( b. shape)
c = np. empty( b. shape)
print ( "\n" , c)
print ( "\n" , x+ y, "\n" )
[[1]
[2]
[4]]
[4 5 6]
<numpy.broadcast object at 0x000001859F9C4EE0>
<numpy.flatiter object at 0x000001859B715F20>
<numpy.flatiter object at 0x000001859FAE0E10>
1 4
1 5
1 6
2 4
2 5
2 6
4 4
4 5
4 6
(3, 3)
[[6.23042070e-307 4.67296746e-307 1.69121096e-306]
[1.11258192e-307 1.89146896e-307 7.56571288e-307]
[3.11525958e-307 1.24610723e-306 2.56765117e-312]]
[[ 5 6 7]
[ 6 7 8]
[ 8 9 10]]
broadcast_to()
原型:numpy.broadcast_to(array,shape,subok = False)
作用:将数组广播到新形状。它在原始数组上返回只读视图。它通常不连续。如果新形状不符合numpy的广播规则,则该函数可能抛出ValueError
参数 说明
array 待修改的形状
shape 修改后的形状
import numpy as np
arr = np. arange( 1 , 5 ) . reshape( 1 , 4 )
arr2= np. broadcast_to( arr, ( 5 , 4 ) )
print ( arr2)
[[1 2 3 4]
[1 2 3 4]
[1 2 3 4]
[1 2 3 4]
[1 2 3 4]]
expand_dims
原型:numpy.squeeze(arr,axis = None)
作用:通过在指定位置插入新的轴来扩展数组
参数 说明
arr 输入数组
axis 新轴插入的位置
import numpy as np
arr = np. arange( 1 , 5 ) . reshape( 2 , 2 )
arr2 = np. expand_dims( arr, 0 )
print ( "arr:\n" , arr, "\n" )
print ( "\n" , arr. shape, "\n" )
print ( "arr:\n" , arr2, "\n" )
print ( "\n" , arr2. shape, "\n" )
arr:
[[1 2]
[3 4]]
(2, 2)
arr:
[[[1 2]
[3 4]]]
(1, 2, 2)
squeeze()
原型:numpy.squeeze(arr,axis)
作用:从给定数组的形状中删除一维的条目
注意:只有轴为1才能删除,但凡大于1都不行
参数 说明
arr 输入数组
axis 删除轴的位置
import numpy as np
arr = np. arange( 1 , 13 ) . reshape( 1 , 1 , 3 , 4 )
print ( arr, "\n" )
print ( arr. shape, "\n" )
arr2 = np. squeeze( arr)
print ( arr2, "\n" )
print ( arr2. shape, "\n" )
arr3 = np. squeeze( arr, 1 )
print ( arr3, "\n" )
print ( arr3. shape, "\n" )
arr4 = np. arange( 1 , 61 ) . reshape( 3 , 1 , 4 , 5 )
arr5 = np. squeeze( arr4)
print ( arr4, "\n" )
print ( arr4. shape, "\n" )
print ( arr5, "\n" )
print ( arr5. shape, "\n" )
[[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]]]
(1, 1, 3, 4)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]]
(1, 3, 4)
[[[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]]
[[[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]
[36 37 38 39 40]]]
[[[41 42 43 44 45]
[46 47 48 49 50]
[51 52 53 54 55]
[56 57 58 59 60]]]]
(3, 1, 4, 5)
[[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]]
[[21 22 23 24 25]
[26 27 28 29 30]
[31 32 33 34 35]
[36 37 38 39 40]]
[[41 42 43 44 45]
[46 47 48 49 50]
[51 52 53 54 55]
[56 57 58 59 60]]]
(3, 4, 5)
一定要支持作者哦