NumPy | 05 创建数组

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

一、numpy.empty

numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组:

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

参数说明:

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

一个创建空数组的实例:

import numpy as np 
x = np.empty([3,2], dtype = int) 
print (x)

输出结果为:

[[ 6917529027641081856  5764616291768666155] [ 6917529027641081859 -5764598754299804209] [ 4497473538 844429428932120]]

注意:数组元素为随机值,因为它们未初始化。

二、numpy.zeros

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

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

参数说明:

参数 描述
shape 数组形状
dtype 数据类型,可选
order 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组
import numpy as np
 
# 默认为浮点数
x = np.zeros(5) 
print(x)
 
# 设置类型为整数
y = np.zeros((5,), dtype = np.int) 
print(y)
 
# 自定义类型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])  
print(z)

输出结果为:

[0. 0. 0. 0. 0.] [0 0 0 0 0] [[(0, 0) (0, 0)] [(0, 0) (0, 0)]]

三、numpy.ones

创建指定形状的数组,数组元素以 1 来填充:

numpy.ones(shape, dtype = None, order = 'C')

参数说明:

参数 描述
shape 数组形状
dtype 数据类型,可选
order 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组

import
numpy as np # 默认为浮点数 x = np.ones(5) print(x) # 自定义类型 x = np.ones([2,2], dtype = int) print(x)

输出结果为:

[1. 1. 1. 1. 1.] [[1 1] [1 1]]




补充

1. Numpy 创建标准正态分布数组:

from numpy import *

# 创建 randn(size) 服从 X~N(0,1) 的正态分布随机数组
a=random.randn(2,3)
print(a)

输出结果为:

[[-0.66177595 -1.53115428 -0.04670656]
[-0.16835942 -1.0587631 0.95134199]]

 

2.Numpy 创建随机分布整数型数组。

利用 randint([low,high],size) 创建一个整数型指定范围在 [low.high] 之间的数组:

from numpy import *

a=random.randint(100,200,(3,3))
print(a)

输出结果为:

[[122 184 187]
[139 157 134]
[157 163 138]]

 

3. arange 创建数组 *****

import numpy as np

a = np.arange(10)
b = np.arange(10, 20)
c = np.arange(10, 20, 2)

print(a)
print(b)
print(c)

输出:

[0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]
[10 12 14 16 18]

4. eye 创建对角矩阵数组

import numpy as np

a = np.eye(5)
print(a)

输出:

[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]




猜你喜欢

转载自www.cnblogs.com/Summer-skr--blog/p/11688763.html