Loading

Numpy之数组创建

ndarray 数组除了可以使用 ndarray 构造器来创建外,也可以通过如下方式创建。

一、创建数组

numpy.empty

语法: numpy.empty(shape, dtype = float, order = 'C') 

参数解释:

  • shape  数组形状
  • dtype  数据类型,可选
  • order  有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

  x = np.empty([2,4],dtype=np.int_,order='c') #这里创建了一个空的数组,数组元素为随机值,因为它们未初始化  

numpy.zeros

创建指定大小的数组,数组元素以 0 来填充

语法: numpy.zeros(shape, dtype = float, order = 'C') 

 y = np.zeros([4,5],dtype=np.int_,order='c') 

print一下y发现是4行5列,以0填充的数组

numpy.ones同理

二、从已有的数组创建数组

numpy.asarray 

numpy.asarray 类似 numpy.array,但 numpy.asarray 只有三个,比 numpy.array 少两个。

语法: numpy.asarray(a, dtype = None, order = None) 

li = [1,2,3]
tu = (1,2,3)
tu_li = [(1,2),(3)]
x = np.asarray(li) #将列表转换为ndarray
y = np.asarray(tu) #将元组转换为ndarray
z = np.asarray(tu_li) #将元组列表转换为ndarray
zz = np.asarray(li,dtype=np.float) #抓换的同时设置参数
print(x)
print(y)
print(z)
print(zz)

numpy.frombuffer

用于实现动态数组。接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象

语法: numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0) 

参数说明:

  • buffer  可以是任意对象,会以流的形式读入。
  • dtype  返回数组的数据类型,可选
  • count  读取的数据数量,默认为-1,读取所有数据。
  • offset  读取的起始位置,默认为0。
s =  'Hello World'
a = np.frombuffer(s,dtype = 'S1')
print (a)

但是这段代码在打印的时候有错误 提示 AttributeError: 'str' object has no attribute '__buffer__' 

因为buffer 是字符串的时候,Python3 默认 str 是 Unicode 类型,所以要转成 bytestring 在原 str 前加上 b。 s = b'Hello World' 

numpy.fromiter

从可迭代对象中建立 ndarray 对象,返回一维数组。

语法: numpy.fromiter(iterable, dtype, count=-1) 

  • iterable  可迭代对象
  • dtype  返回数组的数据类型
  • count  读取的数据数量,默认为-1,读取所有数据 
my_list = range(20) #创建列表对象
it = iter(my_list)
x = np.fromiter(it,dtype=np.float) #使用迭代器创建ndarray对象
print(x)

三、从数值范围创建数组

 

numpy.arange

语法: numpy.arange(start, stop, step, dtype) 

start  起始值,默认为0
stop  终止值(不包含)
step  步长,默认为1
dtype  返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型。

 x = np.arange(1,21,2,dtype=np.float) 

以上输出的类型设置为了float,表示从1到21里面每隔两个数取一次值

numpy.linspace

用于创建一个一维数组,数组是一个等差数列构成的

语法: np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 

start  序列的起始值
stop  序列的终止值,如果endpoint为true,该值包含于数列中
num  要生成的等步长的样本数量,默认为50
endpoint  该值为 ture 时,数列中中包含stop值,反之不包含,默认是True。
retstep  如果为 True 时,生成的数组中会显示间距,反之不显示。
dtype  ndarray 的数据类型

y1 = np.linspace(1,10,10) #起始为1,终止为10,数列个数为10
y2 = np.linspace(1,1,10) #元素全部为1,且有10个数列
y3 = np.linspace(10,20,5,endpoint=False) #设置为False则不包含终止位置
y4 = np.linspace(1,10,10,retstep=True) #显示间距

numpy.logspace

用于创建一个等比数列

语法: np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None) 

start  序列的起始值为:base ** start
stop  序列的终止值为:base ** stop。如果endpoint为true,该值包含于数列中
num  要生成的等步长的样本数量,默认为50
endpoint  该值为 ture 时,数列中中包含stop值,反之不包含,默认是True
base  对数 log 的底数
dtype  ndarray 的数据类型

x1 = np.logspace(1.0,2.0,num=10) #生成底数为10,从1到2的数列
x2 = np.logspace(0,9,10,base=2) #这里的底数为2

 

posted @ 2019-01-24 16:44  ChanceySolo  阅读(314)  评论(0)    收藏  举报