Home >Backend Development >Python Tutorial >In-depth understanding of NumPy concise tutorial---Array 1

In-depth understanding of NumPy concise tutorial---Array 1

高洛峰
高洛峰Original
2017-02-23 16:50:571975browse

This article mainly introduces a concise tutorial for in-depth understanding of NumPy (2. Array 1). The NumPy array is a multi-dimensional array object and has certain reference value. Interested friends can refer to it.

My current job is to introduce NumPy into Pyston (a Python compiler/interpreter implemented by Dropbox). During the work process, I had in-depth contact with the NumPy source code, understood its implementation and submitted a PR to fix NumPy bugs. In the process of dealing with NumPy source code and NumPy developers, I found that most of the current Chinese NumPy tutorials are translated or refer to English documents, which leads to many omissions. For example, the broadcast function in NumPy arrays is translated as "broadcast" in almost all Chinese documents. One of the developers of NumPy replied, "broadcast is a compound -- native English speakers can see that it's " broad" + "cast" = "cast (scatter, distribute) broadly, I guess "cast (scatter, distribute) broadly" is probably closer to the meaning (meaning in NumPy)". In view of this, I plan to start a project to write a series of tutorials based on my understanding of NumPy usage and source code level. #NumPy array


The NumPy array is a multi-dimensional array object called an ndarray. It consists of two parts:

##The actual data

  • Metadata describing these data

  • Most operations only target metadata and do not change the underlying actual data

    ##. #There are a few things you need to know about NumPy arrays:

The subscripts of NumPy arrays start from 0.

    ##All in the same NumPy array. The types of elements must be the same
  • ##NumPy array properties

  • Before introducing the NumPy array in detail, let’s first introduce the basic properties of the NumPy array. The dimension of the NumPy array is called rank. The rank of a one-dimensional array is 1, and the rank of a two-dimensional array is 2. By analogy. In NumPy, each linear array is called an axis (axes), and the rank actually describes the number of axes. For example, a two-dimensional array is equivalent to two one-dimensional arrays, where the first one-dimensional array is the same. Each element is a one-dimensional array. So the one-dimensional array is the axes (axes) in NumPy. The first axis is equivalent to the underlying array, and the second axis is the array in the underlying array. The number of axes - rank. , which is the dimension of the array.

The more important ndarray object properties of NumPy are:

##ndarray.ndim: The dimension of the array. (That is, the number of array axes), equal to the rank. The most common is a two-dimensional array (matrix).

#ndarray.shape: represents the dimension of each array. An integer tuple of dimensions. For example, in a two-dimensional array, it represents the "number of rows" and "number of columns" of the array. ndarray.shape returns a tuple, and the length of this tuple is the number of dimensions, which is the ndim attribute.

##ndarray.size: The total number of array elements is equal to the product of the tuple elements in the shape attribute.
  • ndarray.dtype: An object representing the type of elements in the array, which can be created or specified using standard Python types. In addition, you can also use the data types provided by NumPy introduced in the previous article.
  • ndarray.itemsize: The byte size of each element in the array. For example, the itemsiz attribute value of an array whose element type is float64 is 8 (float64 occupies 64 bits, and each byte is 8 in length, so 64/8 takes up 8 bytes). Another example is an array whose element type is complex32. The array item attribute is 4 (32/8).
  • ndarray.data: Buffer containing the actual array elements. Since elements are generally obtained through the index of the array, there is usually no need to use this attribute.
  • Creating an array
  • Let’s first introduce creating an array. There are many ways to create arrays. For example, you can use the array function to create arrays from regular Python lists and tuples. The type of the array created is derived from the element types in the original sequence.​
  • >>> from numpy import *     
    >>> a = array( [2,3,4] )    
    >>> a 
      array([2, 3, 4]) 
    >>> a.dtype 
      dtype('int32') 
    >>> b = array([1.2, 3.5, 5.1])    
    >>> b.dtype 
      dtype('float64')

When created using the array function, the parameter must be a list enclosed by square brackets, and array cannot be called with multiple values ​​as parameters.​

>>> a = array(1,2,3,4)  # 错误 
>>> a = array([1,2,3,4]) # 正确


You can use double sequences to represent two-dimensional arrays, triple sequences to represent three-dimensional arrays, and so on.

>>> b = array( [ (1.5,2,3), (4,5,6) ] )   
>>> b 
  array([[ 1.5, 2. , 3. ], 
      [ 4. , 5. , 6. ]])

You can explicitly specify the type of elements in the array when creating it

>>> c = array( [ [1,2], [3,4] ], dtype=complex) 
>>> c 
  array([[ 1.+0.j, 2.+0.j], 
     [ 3.+0.j, 4.+0.j]])

Usually, the elements of the array are unknown at the beginning, but the size of the array is known. Therefore, NumPy provides some functions for creating arrays using placeholders. These functions help meet the need for array expansion while reducing the high computational overhead.

Use function zeros to create an array of all 0s, use function ones to create an array of all 1s, and function empty to create an array with random content and dependent on the memory state. The array types (dtype) created by default are float64.

You can use d.dtype.itemsize to check the number of bytes occupied by the elements in the array.

>>> d = zeros((3,4)) 
>>> d.dtype 
dtype('float64') 
>>> d 
array([[ 0., 0., 0., 0.], 
    [ 0., 0., 0., 0.], 
    [ 0., 0., 0., 0.]]) 
>>> d.dtype.itemsize 
8

You can also specify the type of elements in the array yourself

>>> ones( (2,3,4), dtype=int16 ) #手动指定数组中元素类型 
   array([[[1, 1, 1, 1], 
       [1, 1, 1, 1], 
       [1, 1, 1, 1]], 
    
       [[1, 1, 1, 1], 
       [1, 1, 1, 1], 
       [1, 1, 1, 1]]], dtype=int16) 
>>> empty((2,3)) 
   array([[ 2.65565858e-316,  0.00000000e+000,  0.00000000e+000], 
       [ 0.00000000e+000,  0.00000000e+000,  0.00000000e+000]])

NumPy提供一个类似arange的函数返回一个数列形式的数组:

>>> arange(10, 30, 5) 
  array([10, 15, 20, 25])

以10开始,差值为5的等差数列。该函数不仅接受整数,还接受浮点参数: 

>>> arange(0,2,0.5) 
  array([ 0. , 0.5, 1. , 1.5])

当arange使用浮点数参数时,由于浮点数精度有限,通常无法预测获得的元素个数。因此,最好使用函数linspace去接收我们想要的元素个数来代替用range来指定步长。linespace用法如下,将在通用函数一节中详细介绍。

>>> numpy.linspace(-1, 0, 5) 
    array([-1. , -0.75, -0.5 , -0.25, 0. ])

数组中的元素是通过下标来访问的,可以通过方括号括起一个下标来访问数组中单一一个元素,也可以以切片的形式访问数组中多个元素。关于切片访问,将在切片一节介绍。

知识点:NumPy中的数据类型

对于科学计算来说,Python中自带的整型、浮点型和复数类型远远不够,因此NumPy中添加了许多数据类型。如下:

NumPy中的基本数据类型


NumPy中的基本数据类型
名称 描述
bool 用一个字节存储的布尔类型(True或False)
inti 由所在平台决定其大小的整数(一般为int32或int64)
int8 一个字节大小,-128 至 127
int16 整数,-32768 至 32767
int32 整数,-2 ** 31 至 2 ** 32 -1
int64 整数,-2 ** 63 至 2 ** 63 - 1
uint8 无符号整数,0 至 255
uint16 无符号整数,0 至 65535
uint32 无符号整数,0 至 2 ** 32 - 1
uint64 无符号整数,0 至 2 ** 64 - 1
float16 半精度浮点数:16位,正负号1位,指数5位,精度10位
float32 单精度浮点数:32位,正负号1位,指数8位,精度23位
float64或float 双精度浮点数:64位,正负号1位,指数11位,精度52位
complex64 复数,分别用两个32位浮点数表示实部和虚部
complex128或complex 复数,分别用两个64位浮点数表示实部和虚部

NumPy类型转换方式如下:

>>> float64(42) 
  42.0 
>>> int8(42.0) 
  42 
>>> bool(42) 
  True 
>>> bool(42.0) 
  True 
>>> float(True) 
  1.0

许多函数的参数中可以指定参数的类型,当然,这个类型参数是可选的。如下:

>>> arange(7, dtype=uint16) 
  array([0, 1, 2, 3, 4, 5, 6], dtype=uint16)

输出数组

当输出一个数组时,NumPy以特定的布局用类似嵌套列表的形式显示:

  • 第一行从左到右输出

  • 每行依次自上而下输出

  • 每个切片通过一个空行与下一个隔开

  • 一维数组被打印成行,二维数组成矩阵,三维数组成矩阵列表。 

>>> a = arange(6)             # 1d array 
>>> print a 
  [0 1 2 3 4 5] 
    
>>> b = arange(12).reshape(4,3)      # 2d array 
>>> print b 
  [[ 0 1 2] 
  [ 3 4 5] 
  [ 6 7 8] 
  [ 9 10 11]]    
>>> c = arange(24).reshape(2,3,4)     # 3d array 
>>> print c 
  [[[ 0 1 2 3] 
  [ 4 5 6 7] 
  [ 8 9 10 11]] 
    
  [[12 13 14 15] 
  [16 17 18 19] 
  [20 21 22 23]]]

 reshape将在下一篇文章中介绍 

如果一个数组太长,则NumPy自动省略中间部分而只打印两端的数据:   

>>> print arange(10000) 
   [  0  1  2 ..., 9997 9998 9999] 
    
>>> print arange(10000).reshape(100,100) 
   [[  0  1  2 ...,  97  98  99] 
    [ 100 101 102 ..., 197 198 199] 
    [ 200 201 202 ..., 297 298 299] 
    ..., 
    [9700 9701 9702 ..., 9797 9798 9799] 
    [9800 9801 9802 ..., 9897 9898 9899] 
    [9900 9901 9902 ..., 9997 9998 9999]]

可通过设置printoptions参数来禁用NumPy的这种行为并强制打印整个数组。

set_printoptions(threshold='nan')

这样,输出时数组的所有元素都会显示出来。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多深入理解NumPy简明教程---数组1相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn