您的当前位置:首页正文

Numpy:简介与数组

来源:九壹网

a3 = np.array(range(6),dtype=“i1”)

print(a1,a1.dtype)

print(a2,a2.dtype)

print(a3,a3.dtype)

‘’’

[0. 1. 2. 3.] float64

[0. 1. 2. 3. 4.] float16

[0 1 2 3 4 5] int8

‘’’




**(3)数组创建好后修改数据类型:array.astype(数据类型)**



a22 = a2.astype(int)

a33 = a3.astype(‘float16’)

print(a22.dtype,a33.dtype)

‘’’

int32 float16

‘’’




**(4)Numpy中的bool类型**



创建时指定bool类型,将一个列表中的数据转换成True或False



转换规则在与Python中相同: **0 / 空字符串’’ / None都为False,其他都为True**



s1 = np.array([2,0,1,None,‘’,‘ssd’,True],dtype=bool)

print(s1,s1.dtype)

‘’’

[ True False True False False True True] bool

‘’’




**(5)Numpy中的小数类型**



numpy.round(array, n) 将array中的小数保留n位并返回数组



s2 = np.array([random.random() for i in range(5)])

创建数组时使用列表循环

print(s2,s2.dtype)

s3 = np.round(s2,3)

Numpy.round(array,n) 将array中保留n位小数,并返回数组

print(s3,s3.dtype)

‘’’

[0.49257971 0.35290744 0.35157731 0.02503256 0.06226811] float64

[0.493 0.353 0.352 0.025 0.062] float64

‘’’




### []( )数组的形状(数组的多维形式)



#### []( )array.shape



返回该数组有几行几列,元组类型,层次以此类推



由于shape()返回元组类型,我们可以用shape\[0\]获取行数,shape\[1\]获取列数



一维数组

a1 = np.array([1,3,5,2])

print(a1.shape)

二维数组

a2 = np.array([

[11,12,13],

[21,22,23]

])

print(a2.shape)

print(‘a2共有%d个元素’ %(a2.shape[0]*a2.shape[1]) )

三维数组

a3 = np.array([

[

    [111,112,113],

    [121,122,123]

],

[

    [211,212,213],

    [221,222,223]

]

])

print(a3)

print(a3.shape)

print(‘a2共有%d个元素’ %(a3.shape[0]*a3.shape[1]) )

‘’’

(4,)

(2, 3)

a2共有6个元素

(2, 2, 3)

a2共有4个元素

‘’’

a4 = np.array(

[23],

[23,25]

)

每一行的列数必须相等,否则会报错:

print(a4.shape)

TypeError: Field elements must be 2- or 3-tuples, got ‘23’




#### []( )array.reshape( (n,m,…) )



将数组转换成n行m列的多维数组,元素个数必须刚刚好,否则报错



返回转换后的数组,但不改变原数组



a5 = np.arange(6)

print(a5.reshape((2,3))) # 转换成2行3列的二维数组

print(a5.reshape(6)) # 转换回一维数组

a6 = np.arange(27)

print(a6.reshape((3,3,3)))

‘’’

[[0 1 2]

[3 4 5]]

[[[ 0 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]]]

‘’’




#### []( )array.flatten()



将二维数组转换为一维数组



返回转换后的数组,但不改变原数组



a5 = np.array([ [1,2,3], [4,5,6]])print(a5.flatten())‘’‘[1 2 3 4 5 6]’‘’




### []( )数组的运算



对数组进行运算时会将运算过程作用于每一个元素(numpy的广播机制)



如果运算为除以零,会返回nan(0/0 Not A Number) 或者 inf(n/0 infinite)

因篇幅问题不能全部显示,请点此查看更多更全内容

Top