#ndarray数组定义#用np.ndarray类的对象表示n维数组import numpy as np
ary = np.array([1,2,3,4,5,6])print(type(ary),ary)
<class 'numpy.ndarray'> [1 2 3 4 5 6]
#ndarry数组创建np.array(object,dtype = None , copy = True, order = None, subok = False, ndmin = 0)#object 数组或嵌套的数列#dtype 数组元素的数据类型,可选#copy 对象是否需要复制,可选#order 创建数组的样式,C为行方向,F为列方向,A为任意方向(默认)#ndmin 制定生成数组的最小维度
array(<class 'object'>, dtype=object)
import numpy as np #用np代替numpy,让代码更简洁
a = [1,2,3,4,5] #创建列表a
b = np.array(a) #从列表a创建数组b,array就是数组的意思
print(a)
print(type(a))# 打印a的类型
print(b)
print(type(b)) #打印b的类型
#观察输出值的区别 列表和数组的区别,列表中间有逗号 数组没有逗号
[1, 2, 3, 4, 5]
<class 'list'>
[1 2 3 4 5]
<class 'numpy.ndarray'>
创建数组的几种方式
#创建数组的几种方式
#1、创建一维数组和二维数组
c = np.array([5,6,7,8])
print(c)
print(type(c))
d = np.array([[1,2],[3,4],[5,6]])
print(d)
print(type(d))
[5 6 7 8]
<class 'numpy.ndarray'>
[[1 2]
[3 4]
[5 6]]
<class 'numpy.ndarray'>
#2、第二种创建方式:np.arange(start , end , step), dtype)
#1个参数:参数值为终止值,起始值默认0,步长1,左闭右开
x = np.arange(5)
print(x)
#2个参数,参数值为起始值。终止值,步长默认1,左闭右开
y = np.arange(5,10)
print(y)
#3个参数:参数值为起始值,终止值,步长为2 ,左闭右开
z = np.arange(10,20,2)
print(z)
[0 1 2 3 4]
[5 6 7 8 9]
[10 12 14 16 18]
#3、np.zeros(数组元素个数,dtype='类型')
#格式:np.zeros(shape,dtype = float, order = 'C')
e = np.zeros(10)
print(e)
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
#4、np.ones(数组元素个数,dtype=('类型'))
#格式:np.ones(shape,dtype = None, order = 'C')
f = np.ones(10)
print(f)
[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
#5、np.random中的函数来创建随机一维数组
#创建一个一维数组,其中包含服从标准正态分布(均值0,标准差为1的分布)的n个随机数
g = np.random.randn(5)
print(g)
[-1.31712585 1.73631151 -0.11465625 0.44074883 -0.64635164]
# 生成一维数组中包含的就是0~1之间的n个随机数
h = np.random.rand(6)
print(h)
[0.00618959 0.24149481 0.55112033 0.30985714 0.42426622 0.60379981]
#其他函数
#zeros_like, ones_like,empty,empty_like, linspace,numpy.random.generator.rand......
# 6、numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组
# numpy.empty(shape,dtype = float, order = 'C')
x = np.empty((3,2),dtype = int)
print(x)
[[1677818880 1677943810]
[1677884418 1392938244]
[1627728128 1290]]
# 7、numpy.linspace 函数用来创建一个一维数组,数组是一个等差数列
#np.linspace(start, stop,num = 50,endpoint= True,retstep=False,dtype=None)
#start序列的起始值#stop序列的终止值,如果endpoint为true,该值包含在数列中#num要生成的等步长的样本数量,默认为50
#endpoint 该值为true时,数列中包含stop值,反之不包含,默认是true
#retstep 如果为true时,生成的数组中间会显示间距,反之不显示
#dtype ndarray的数据类型
aa = np.linspace(1,10,10)
print(aa)
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
#8、创建二维数组
#创建一维数组的np.arange()函数和reshape()函数来创建二维数组
#创建一个3行4列的二维数组
i = np.arange(12).reshape(3,4)
print(i)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
#np.random.randint()函数用于创建随机整数数组
j = np.random.randint(0,10,(4,4))
print(j)
#第一个参数0为起始值,第二个参数值10为终止数,第三个参数(4,4)表示一个四行四列的二维数组
[[1 7 2 8]
[4 0 6 3]
[6 0 2 1]
[3 6 4 8]]
#9、从已有的数组创建数组
#numpy.asarray类似numpy.array,但numpy.asarray参数只有三个,比numpy.array少两个
# 格式:numpy.asarray(a, dtype = None,order = None)
lst = [[1,2,3],[4,5,6]]
array01 = np.asarray(lst,dtype=int, order= 'F')
print(array01)
[[1 2 3]
[4 5 6]]
import numpy as np
array11 = np.array([1,2,3,4,5,6],order = 'F')
print(array11)
[1 2 3 4 5 6]