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

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

Feb 23, 2017 pm 04:50 PM

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.​
  • 1

    2

    3

    4

    5

    6

    7

    8

    9

    >>> 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')

    Copy after login

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.​

1

2

>>> a = array(1,2,3,4)  # 错误

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

Copy after login


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

1

2

3

4

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

>>> b

  array([[ 1.5, 2. , 3. ],

      [ 4. , 5. , 6. ]])

Copy after login

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

1

2

3

4

>>> c = array( [ [1,2], [3,4] ], dtype=complex)

>>> c

  array([[ 1.+0.j, 2.+0.j],

     [ 3.+0.j, 4.+0.j]])

Copy after login

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.

1

2

3

4

5

6

7

8

9

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

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

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

Copy after login

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

1

2

>>> arange(10, 30, 5)

  array([10, 15, 20, 25])

Copy after login

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

1

2

>>> arange(0,2,0.5)

  array([ 0. , 0.5, 1. , 1.5])

Copy after login

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

1

2

>>> numpy.linspace(-1, 0, 5)

    array([-1. , -0.75, -0.5 , -0.25, 0. ])

Copy after login

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

知识点: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类型转换方式如下:

1

2

3

4

5

6

7

8

9

10

>>> float64(42)

  42.0

>>> int8(42.0)

  42

>>> bool(42)

  True

>>> bool(42.0)

  True

>>> float(True)

  1.0

Copy after login

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

1

2

>>> arange(7, dtype=uint16)

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

Copy after login

输出数组

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

  • 第一行从左到右输出

  • 每行依次自上而下输出

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

Copy after login

reshape将在下一篇文章中介绍 

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

1

2

3

4

5

6

7

8

9

10

11

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

Copy after login

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

1

set_printoptions(threshold='nan')

Copy after login

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

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

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


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles