Numpy 简明教程
NumPy - Ndarray Object
NumPy 中定义的最重要的对象是一个 N 维数组类型,称为 ndarray 。它描述同类型的项的集合。可以使用基于零的索引访问集合中的项。
The most important object defined in NumPy is an N-dimensional array type called ndarray. It describes the collection of items of the same type. Items in the collection can be accessed using a zero-based index.
ndarray 中的每一项在内存中占用相同大小的块。ndarray 中的每个元素都是数据类型对象(称为 dtype )。
Every item in an ndarray takes the same size of block in the memory. Each element in ndarray is an object of data-type object (called dtype).
从 ndarray 对象(通过切片)提取的任何项都通过一种数组标量类型表示为一个 Python 对象。下图展示了 ndarray、数据类型对象 (dtype) 与数组标量类型之间的关系:
Any item extracted from ndarray object (by slicing) is represented by a Python object of one of array scalar types. The following diagram shows a relationship between ndarray, data type object (dtype) and array scalar type −
在之后教程中所述的不同数组创建例程中,可以构造 ndarray 类的实例。使用 NumPy 中的数组函数按如下方式创建基本 ndarray:
An instance of ndarray class can be constructed by different array creation routines described later in the tutorial. The basic ndarray is created using an array function in NumPy as follows −
numpy.array
它通过公开数组接口的任意对象或通过返回数组的任意方法创建 ndarray。
It creates an ndarray from any object exposing array interface, or from any method that returns an array.
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
上述构造函数接受以下参数:
The above constructor takes the following parameters −
Sr.No. |
Parameter & Description |
1 |
object Any object exposing the array interface method returns an array, or any (nested) sequence. |
2 |
dtype Desired data type of array, optional |
3 |
copy Optional. By default (true), the object is copied |
4 |
order C (row major) or F (column major) or A (any) (default) |
5 |
subok By default, returned array forced to be a base class array. If true, sub-classes passed through |
6 |
ndmin Specifies minimum dimensions of resultant array |
仔细查看以下示例,以便更好地理解。
Take a look at the following examples to understand better.
Example 1
import numpy as np
a = np.array([1,2,3])
print a
输出如下 −
The output is as follows −
[1, 2, 3]
Example 2
# more than one dimensions
import numpy as np
a = np.array([[1, 2], [3, 4]])
print a
输出如下 −
The output is as follows −
[[1, 2]
[3, 4]]
Example 3
# minimum dimensions
import numpy as np
a = np.array([1, 2, 3,4,5], ndmin = 2)
print a
输出如下 −
The output is as follows −
[[1, 2, 3, 4, 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print a
输出如下 −
The output is as follows −
[ 1.+0.j, 2.+0.j, 3.+0.j]
ndarray 对象由连续的一维计算机内存段组成,该段与一个索引方案结合在一起,将每个项目映射到内存块中的一个位置。内存块按行优先顺序 (C 样式) 或列优先顺序 (FORTRAN 或 MatLab 样式) 保存元素。
The ndarray object consists of contiguous one-dimensional segment of computer memory, combined with an indexing scheme that maps each item to a location in the memory block. The memory block holds the elements in a row-major order (C style) or a column-major order (FORTRAN or MatLab style).