NumPy教程:数组创建例程—ndarray对象或构造函数

2018-09-2710:08:13后端程序开发Comments2,380 views字数 1092阅读模式

NumPy - 数组创建例程

新的ndarray对象可以通过任何下列数组创建例程或使用低级ndarray构造函数构造。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

numpy.empty

它创建指定形状和dtype的未初始化数组。 它使用以下构造函数:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

构造器接受下列参数:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

序号参数及描述
1.Shape 空数组的形状,整数或整数元组
2.Dtype 所需的输出数组类型,可选
3.Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组

示例

下面的代码展示空数组的例子:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

输出如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

[[22649312    1701344351] 
 [1818321759  1885959276] 
 [16779776    156368896]]

注意:数组元素为随机值,因为它们未初始化。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

numpy.zeros

返回特定大小,以 0 填充的新数组。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

构造器接受下列参数:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

序号参数及描述
1.Shape 空数组的形状,整数或整数元组
2.Dtype 所需的输出数组类型,可选
3.Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组

示例 1

# 含有 5 个 0 的数组,默认类型为 float  
import numpy as np 
x = np.zeros(5)  
print x

输出如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

示例 2

import numpy as np 
x = np.zeros((5,), dtype = np.int)  
print x

输出如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

[0  0  0  0  0]

示例 3

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

输出如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

numpy.ones

返回特定大小,以 1 填充的新数组。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

构造器接受下列参数:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

序号参数及描述
1.Shape 空数组的形状,整数或整数元组
2.Dtype 所需的输出数组类型,可选
3.Order 'C'为按行的 C 风格数组,'F'为按列的 Fortran 风格数组

示例 1

# 含有 5 个 1 的数组,默认类型为 float  
import numpy as np 
x = np.ones(5)  print x

输出如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

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

示例 2

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

输出如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html

[[1  1] 
 [1  1]]
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/5870.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/5870.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定