创建
import numpy as np
v=np.arange(10)
print(v)
print(v.dtype) #类型int32
print(v.shape) #(10,)
v2=np.arange(0,10,0.5) #以0.5为间隔
v2
#array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])
v2*10#运算array([ 0., 5., 10., 15., 20., 25., 30., 35., 40., 45., 50., 55., 60.,65., 70., 75., 80., 85., 90., 95.])
np.linspace(1,19,10,endpoint=False)#在1-19中取10个数不算19
#array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. , 11.8, 13.6, 15.4, 17.2])
np.zeros(20,np.int)
#array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
np.random.randn(10)#正态分布函数
#array([-0.39637347, -0.35121478, -0.11757261, 0.16162262, -1.00789176,-1.50757114, -0.37636566, 0.4447863 , -0.28202346, -0.20686239])
a=np.array([np.arange(1,3),np.arange(1,3)])#创建多维数组
#array([[1, 2],
# [1, 2]])
np.identity(9).astype(np.int8)
'''array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=int8)'''
将数组转为列表
a.tolist()
查询numpy的所有数据格式
print(set(np.typeDict.values()))
'''{<class 'numpy.uint32'>, <class 'numpy.int16'>,
<class 'numpy.uint64'>, <class 'numpy.intc'>,
<class 'numpy.int8'>, <class 'numpy.object_'>,
<class 'numpy.float64'>, <class 'numpy.bool_'>,
<class 'numpy.float32'>, <class 'numpy.datetime64'>, <class 'numpy.str_'>, <class 'numpy.complex64'>,
<class 'numpy.uint16'>, <class 'numpy.bytes_'>,
<class 'numpy.float16'>, <class 'numpy.clongdouble'>, <class 'numpy.int32'>, <class 'numpy.timedelta64'>,
<class 'numpy.complex128'>, <class 'numpy.uintc'>, <class 'numpy.int64'>, <class 'numpy.void'>,
<class 'numpy.longdouble'>, <class 'numpy.uint8'>}'''
创建结构数组
#方法一
goodlist=np.dtype([('name',np.str_,50),('location',np.str_,30),
('price',np.float16),('volume',np.int32)])
goodlist
#方法二
goodsdict=np.dtype({
'names':['name','location','price','volume'],
'formats':['U50','U30','f','i']})
goods=np.array([('GA','JD.com',4223,1),
('SN','BL.com',6453,2)],dtype=goodlist)
goods
三维数组+定型
b=np.arange(24).reshape(2,3,4)#不会修改原始数据
b
ac=np.arange(12)
ac
ac.shape=(2,2,3) #会修改原始数据
ac
'''array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])'''
切片
b[1,:,1]
#array([13, 17, 21])
b[0,::2,-2]#第0层 格一行选倒数第二个
#array([ 2, 10])
b[b>=15]
#array([15, 16, 17, 18, 19, 20, 21, 22, 23])
转置
print(ac.T)
np.transpose(b)
降维
ab=np.ravel(ac)
ab
数组组合(行)
列
数组分拆
数组的常用属性