NumPy学习笔记04.创建数组

NumPy 创建数组

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)
# 输出数组元素为随机值,因为它们未初始化
[[        648           0]
 [ 1267083696         613]
 [          0 -2147483648]]

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]]

学习参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZPILOTE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值