NumPy 4 - 创建数组

NumPy 创建数组



原文地址:

https://www.runoob.com/numpy/numpy-array-creation.html


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

1、numpy.empty

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

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

参数说明:

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

使用


2、numpy.zeros

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

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

参数说明:

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

使用

# numpy.zeros 创建指定大小的数组,数组元素以 0 来填充:
# 默认为浮点数
b = np.zeros(5)
print(b)  # [0. 0. 0. 0. 0.]

print('-----------')

# 设置类型为整数
c = np.zeros((5,), dtype=np.int)
print(c)  # [0 0 0 0 0]

print('-----------')

# 自定义类型
d = np.zeros((2, 2), dtype=[('x', 'i4'), ('y', 'i4')])
print(d)
'''
[[(0, 0) (0, 0)]
 [(0, 0) (0, 0)]]
'''


print(d['x'])
'''
[[0 0]
 [0 0]]
 '''

3、numpy.ones

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

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

参数说明:

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


# numpy.ones 创建指定形状的数组,数组元素以 1 来填充:
# 默认为浮点数
e = np.ones(5)  # [1. 1. 1. 1. 1.]
print(e)

# 自定义类型
x = np.ones([2,2], dtype = int)
print(x)
'''
[[1 1]
 [1 1]]
'''

从已有的数组创建数组

4、numpy.asarray

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

numpy.asarray(a, dtype = None, order = None)

参数说明:

参数 描述
a 任意形式的输入参数,可以是,列表, 列表的元组, 元组, 元组的元组, 元组的列表,多维数组
dtype 数据类型,可选
order 可选,有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。

实例


g = [1,2,3]
h = np.asarray(g)
print(h)  # [1 2 3]

# 元组 转 ndarray
j =  (1,2,3)
h = np.asarray(j)
print(h) # [1 2 3]

# 元组列表 转 ndarray
k =  [(1,2,3),(4,5)]
h = np.asarray(k)
print(h)  # [(1, 2, 3) (4, 5)]

# 设置了 dtype 参数
h = np.asarray(g, dtype = float)
print(h)  # [1. 2. 3.]

5、numpy.frombuffer

numpy.frombuffer 用于实现动态数组。

numpy.frombuffer 接受 buffer 输入参数,以流的形式读入转化成 ndarray 对象。

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

**注意:**buffer 是字符串的时候,Python3 默认 str 是 Unicode 类型,所以要转成 bytestring 在原 str 前加上 b。

参数说明:

参数 描述
buffer 可以是任意对象,会以流的形式读入。
dtype 返回数组的数据类型,可选
count 读取的数据数量,默认为-1,读取所有数据。
offset 读取的起始位置,默认为0。


s = b'Hello World'
a = np.frombuffer(s, dtype='S1')
print(a)  # [b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

s =  'Hello World'
a = np.frombuffer(s, dtype =  'S1')
print (a)

Traceback (most recent call last):
  File "/Users/user/PycharmProjects/NumpyDemo/Code/ArrayCreate.py", line 89, in <module>
    a = np.frombuffer(s, dtype =  'S1')
TypeError: a bytes-like object is required, not 'str'


6、numpy.fromiter

numpy.fromiter 方法从可迭代对象中建立 ndarray 对象,返回一维数组。

numpy.fromiter(iterable, dtype, count=-1)
参数 描述
iterable 可迭代对象
dtype 返回数组的数据类型
count 读取的数据数量,默认为-1,读取所有数据

# 使用 range 函数创建列表对象
list = range(5)
it = iter(list)

# 使用迭代器创建 ndarray
x = np.fromiter(it, dtype=float)
print(x)  # [0. 1. 2. 3. 4.]


从数值范围创建数组

7、numpy.arange

numpy 包中的使用 arange 函数创建数值范围并返回 ndarray 对象,函数格式如下:

numpy.arange(start, stop, step, dtype)

根据 start 与 stop 指定的范围以及 step 设定的步长,生成一个 ndarray。

参数说明:

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

# 生成 0 到 5 的数组
x = np.arange(5)
print (x)  # [0 1 2 3 4]


# 设置返回类型位 float (设置了 dtype)
x = np.arange(5, dtype =  float)
print (x)  # [0. 1. 2. 3. 4.]

# 设置了起始值、终止值及步长
x = np.arange(10,20,2)
print (x)  # [10 12 14 16 18]

8、numpy.linspace 创建一维数组

numpy.linspace 函数用于创建一个一维数组,数组是一个等差数列构成的,格式如下:

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

参数说明:

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


# 设置起始点为 1 ,终止点为 10,数列个数为 10。
a = np.linspace(1,10,10)
print(a) # [ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

# 设置元素全部是1的等差数列
a = np.linspace(1,1,10)
print(a)   # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

# 将 endpoint 设为 false,不包含终止值
a = np.linspace(10, 20,  5, endpoint =  False)
print(a)  # [10. 12. 14. 16. 18.]

# 如果将 endpoint 设为 true,则会包含 20。
# 以下实例设置间距。

a = np.linspace(1, 10, 10, retstep=True)
print(a)  # (array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]), 1.0)

# 拓展例子
b = np.linspace(1, 10, 10).reshape([10, 1])
print(b)
'''
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]
 [ 5.]
 [ 6.]
 [ 7.]
 [ 8.]
 [ 9.]
 [10.]]
'''


9、numpy.logspace

numpy.logspace 函数用于创建一个于等比数列。格式如下:

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

base 参数意思是取对数的时候 log 的下标。

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

# 默认底数是 10
a = np.logspace(1.0,  2.0, num =  10)
print (a)
'''
[ 10.          12.91549665  16.68100537  21.5443469   27.82559402
  35.93813664  46.41588834  59.94842503  77.42636827 100.        ]
'''

# 将对数的底数设置为 2
a = np.logspace(0,9,10,base=2)
print (a)  # [  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]


发布了14 篇原创文章 · 获赞 1 · 访问量 956

猜你喜欢

转载自blog.csdn.net/weixin_45390999/article/details/104073424