小白教程
所有教程
关于
Search
108.162.216.25
108.162.216.25
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“NumPy 创建数组”的源代码
本页内容
上一节:
NumPy_数组属性
下一节:
NumPy_从已有的数组创建数组
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:NumPy 创建数组}}[[Category:NumPy 教程|6]] = NumPy 创建数组 = ndarray 数组除了可以使用底层 ndarray 构造器来创建外,也可以通过以下几种方式来创建。 === numpy.empty === numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组: <sample title="" desc="" lang="python" hererun="1"> numpy.empty(shape, dtype = float, order = 'C') </sample> 参数说明: {| class="table table-striped table-hover" ! 参数 ! 描述 |- | shape | 数组形状 |- | dtype | 数据类型,可选 |- | order | 有"C"和"F"两个选项,分别代表,行优先和列优先,在计算机内存中的存储元素的顺序。 |} 下面是一个创建空数组的实例: <sample title="" desc="" lang="python" hererun="1"> import numpy as np x = np.empty([3,2], dtype = int) print (x) </sample> 输出结果为: <sample title="" desc="" lang="python" hererun="1"> [[ 6917529027641081856 5764616291768666155] [ 6917529027641081859 -5764598754299804209] [ 4497473538 844429428932120]] </sample> '''注意''' − 数组元素为随机值,因为它们未初始化。 === numpy.zeros === 创建指定大小的数组,数组元素以 0 来填充: <sample title="" desc="" lang="python" hererun="1"> numpy.zeros(shape, dtype = float, order = 'C') </sample> 参数说明: {| class="table table-striped table-hover" ! 参数 ! 描述 |- | shape | 数组形状 |- | dtype | 数据类型,可选 |- | order | 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组 |} <sample title="" desc="" lang="python" hererun="1"> import numpy as np # 默认为浮点数 x = np.zeros(5) print(x) # 设置类型为整数 y = np.zeros((5,), dtype = int) print(y) # 自定义类型 z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')]) print(z) </sample> 输出结果为: <sample title="" desc="" lang="python" hererun="1"> [0. 0. 0. 0. 0.] [0 0 0 0 0] [[(0, 0) (0, 0)] [(0, 0) (0, 0)]] </sample> === numpy.ones === 创建指定形状的数组,数组元素以 1 来填充: <sample title="" desc="" lang="python" hererun="1"> numpy.ones(shape, dtype = None, order = 'C') </sample> 参数说明: {| class="table table-striped table-hover" ! 参数 ! 描述 |- | shape | 数组形状 |- | dtype | 数据类型,可选 |- | order | 'C' 用于 C 的行数组,或者 'F' 用于 FORTRAN 的列数组 |} <sample title="" desc="" lang="python" hererun="1"> import numpy as np # 默认为浮点数 x = np.ones(5) print(x) # 自定义类型 x = np.ones([2,2], dtype = int) print(x) </sample> 输出结果为: <sample title="" desc="" lang="python" hererun="1"> [1. 1. 1. 1. 1.] [[1 1] [1 1]] </sample>
返回至“
NumPy 创建数组
”。
上一节:
NumPy_数组属性
下一节:
NumPy_从已有的数组创建数组