1.创建数组
(1)numpy.empty
numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组
import numpy as np
x = np.empty([3,2], dtype = int)
print (x)
![Numpy(2)—numpy.empty、numpy.zeros、numpy.ones、numpy.asarray、numpy.arange、numpy.linspace、numpy.logspace_第1张图片](http://img.e-com-net.com/image/info8/7173dcc522c748928d8c1c47e29439fd.jpg)
注意 − 数组元素为随机值,因为它们未初始化
(2)numpy.zeros
创建指定大小的数组,数组元素以 0 来填充
import numpy as np
y = np.zeros((5,), dtype=int)
print(y)
z = np.zeros((2, 2), dtype=[('x', 'i4'), ('y', 'i4')])
print(z)
![Numpy(2)—numpy.empty、numpy.zeros、numpy.ones、numpy.asarray、numpy.arange、numpy.linspace、numpy.logspace_第2张图片](http://img.e-com-net.com/image/info8/53c9262e1af84ebf91da991732b6725c.jpg)
(3)numpy.ones
创建指定形状的数组,数组元素以 1 来填充
import numpy as np
x = np.ones(5)
print(x)
x = np.ones([2, 2], dtype=int)
print(x)
![Numpy(2)—numpy.empty、numpy.zeros、numpy.ones、numpy.asarray、numpy.arange、numpy.linspace、numpy.logspace_第3张图片](http://img.e-com-net.com/image/info8/60fa2f1a344b4bf8a602b833c9c5b167.jpg)
2.NumPy 从已有的数组创建数组
(1) numpy.asarray
将元组转换为ndarray
import numpy as np
x = [(1, 2, 3), (4, 5, 6)]
a = np.asarray(x, dtype=float)
print(a)
![在这里插入图片描述](http://img.e-com-net.com/image/info8/898c307c5a184082b643ae26fdd737dd.jpg)
(2)numpy.frombuffer
numpy.frombuffer 用于实现动态数组
import numpy as np
s = b'Hello World'
a = np.frombuffer(s, dtype = 'S1')
print (a)
![在这里插入图片描述](http://img.e-com-net.com/image/info8/d6ff7e819a5446b0aa84e9599ebb55cc.jpg)
(3)numpy.fromiter
方法从可迭代对象中建立 ndarray 对象,返回一维数组。
import numpy as np
list = range(5)
it = iter(list)
x = np.fromiter(it, dtype=float)
print(x)
![在这里插入图片描述](http://img.e-com-net.com/image/info8/8bb1efa4e367458284d956394953ab25.jpg)
3.NumPy 从数值范围创建数组
(1) numpy.arange
numpy 包中的使用 arange 函数创建数值范围并返回 ndarray 对象
import numpy as np
x = np.arange(10, 20, 2, dtype=float)
print(x)
![在这里插入图片描述](http://img.e-com-net.com/image/info8/0c6a49072bdc486ea6e5841c451c1369.jpg)
(2)numpy.linspace
numpy.linspace 函数用于创建一个一维数组,数组是一个等差数列构成的
import numpy as np
a = np.linspace(1, 10, 10)
print(a)
a = np.linspace(10, 20, 5, endpoint=False)
print(a)
a = np.linspace(1, 10, 10, retstep=True)
print(a)
b =np.linspace(1, 10, 10).reshape([2, 5])
print(b)
![Numpy(2)—numpy.empty、numpy.zeros、numpy.ones、numpy.asarray、numpy.arange、numpy.linspace、numpy.logspace_第4张图片](http://img.e-com-net.com/image/info8/8e1f69b68d6f4d43bccc0d0fc1e142bc.jpg)
(3)numpy.logspace
numpy.logspace 函数用于创建一个于等比数列
import numpy as np
a = np.logspace(1.0, 2.0, num = 10)
print (a)
![在这里插入图片描述](http://img.e-com-net.com/image/info8/4f03f8fbf46b447b99a6728d1ef6472d.jpg)