[advanced Python] do you really understand ndarray in numpy?

There are three words 2021-08-09 15:46:50
advanced python really understand ndarray


 

If you want to master Python, that NumPy It's something you have to master .NumPy It's actually Python An extended library of language , Support high-dimensional array and matrix operations , It provides a large number of mathematical function libraries .

 

1 ndarray Memory mechanism

We know NumPy One of the most important features is its N Dimensional array object ndarray. Usually ndarray The interior consists of .

Data pointer : A pointer to the actual data ;

data type (dtype): Describes the number of bytes occupied by each element in the array ;

dimension (shape): An array shape ( The size of each dimension ) tuples .

span (strides): A represents the number of bytes to cross from the current element to the next element .

Let's look at the following code ndarray The content of :

import numpy as np

a = np.arange(1,25).reshape((2,2,2,3))

print(type(a))

print(a.shape)

print(a.dtype)

print(a.strides)

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

there shape Refers to each dimension Number of elements . The number of elements in each dimension of the four-dimensional array here is 2、2、2 and 3. Why , This seems wrong !2+2+2+3=9, This does not mean 24 ah ! Is my analysis wrong ?

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Of course not. , Let's start with a Output , give the result as follows :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

The innermost floor here [ ] Can represent 1 One dimensional array , There are 3 Elements . A pair of bold red [ ] Represents a two-dimensional array , There are two in it [ ], That is, there are... In the two-dimensional array 2 One dimensional array . Therefore, the number of elements in the third dimension is 2; A pair of bold purple [ ] Represents a three-dimensional array , There are two in it [ ], That is, there are... In the three-dimensional array 2 Two dimensional array . Therefore, the number of elements in the second dimension is 2. Empathy , The number of elements in the first dimension is 2.

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

I believe you should understand by now shape Why are tuples in (2,2,2,3) Is that right .

 

after one's words shape, Let's see dtype, It refers to the array element type , Be careful , The array tuple here refers to 1,2,...,23,24 Such an element . In addition, the type of each element in the array is the same , In this array , Each element in the array is of type int32.

 

Finally, let's analyze the span (strides). It refers to the number of bytes to cross from the current element to the next element .

 

We can see in the above example strides=(48,24,12,4). So how did these four numbers come from ?

 

We're in the four-dimensional array above ,dtype by int, and int Occupy 4 Bytes . And the fourth dimension has 3 Elements , The total number of bytes is 12, Therefore, the number of bytes to be crossed from the fourth dimension to the third dimension is 12; The third dimension has 2 Elements ( One dimensional array ), The total number of bytes of each one-dimensional array is 12, Therefore, the number of bytes to cross from the third dimension to the second dimension is 24. Empathy , The number of bytes spanning from the second dimension to the first dimension is 48.

 

So the span of the four-dimensional array in the above example is (48,24,12,4), Its representation in memory is shown in the following figure :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

It can be clearly seen from the above figure that in order to reach the third dimension ( Axis 2), You have to cross the fourth dimension ( Axis 3), Need to cross 3 Elements , The number of bytes is 12; To reach the first dimension ( Axis 0), You have to cross the second 、 3、 ... and 、 Four dimensions , in total 12 Elements , The number of bytes is 12*4=48.

 

That is to say NumPy How data is stored in . It is stored in a uniform continuous memory block , It's understandable ,NumPy Store multidimensional array in the form of one-dimensional array , We just need to know the number of bytes per element (dtype) And the number of elements in each dimension (shape), You can quickly locate any element of any dimension .

2 NumPy High dimensional array index and transpose

2.1 Indexes

 

When it comes to indexes , You may think it's easy , Don't you just get an element through an index ? The truth is that . But in the face of high-dimensional arrays , It is troublesome to get an element by index .

 

Let's analyze the index of the next four-dimensional array through a case .

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

If I want to get the above 17 This element , What should I do ?

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

First, the four-dimensional array is represented in the form of the axis in the figure above . We You can think of it as four blocks first , Among them the first 0 Shaft and section 1 The axis determines the position of a block , The first 2 Shaft and section 3 The axis determines the specific position of an element in the block .

 

In the picture 17 In the 3 block , As shown in the yellow part below , use 0 Axis and 1 In terms of axes , The index is [1,0].

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Now the position of the block is determined , Next, we determine the location of the elements in the block . As shown in the figure below :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

17 The index of this element in the figure above is [1,1]. Next, we just need to determine the index of the block [1,0] And determine the index of the elements in the block [] according to [ The first 0 Axis , The first 1 Axis , The first 2 Axis , The first 3 Axis ] This format can be merged , In this case , After the merger 17 The index of is [1,0,1,1].

 

Of course , You can use the following code to confirm , Is our analysis correct .

import numpy as np   

a = np.arange(1,25).reshape((2,2,2,3))

print(a[1,0,1,1])  

This is the index of high-dimensional array , Have you understood ?

 

2.2 High dimensional array transpose

 

Transposition of high-dimensional arrays has always been learning NumPy One of the difficulties of , Although in NumPy You only need to call numpy.transpose You can complete the transpose operation , But can you really analyze why the result is like this ? Especially high-dimensional arrays . Let's take a simple example to analyze . as follows :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

The above figure shows the original array , We transpose through the following code , We will get the following results :

import numpy as np
a = np.arange(16).reshape((2,2,4))

b = a.transpose((1,0,2))
print(b)

The result of transposition :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

I believe you have seen the specific difference , That is the exchange of the index order of the axes . Because in the code we require 0 Axis and 1 The shafts are interchangeable , So the result of transposition is actually a[1,0] Will become the original array a[0,1];a[0,1] Will become the original array a[1,0]. If represented by a graph , As shown in the figure below :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

I believe you have understood the principle , Next, leave a question to think about , as follows :

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

Excuse me, , How to transpose from left to right to get !

summary

 

In this issue, we introduce ndarray Memory mechanism and index and transpose of high-dimensional array .NumPy There is still a lot of knowledge about , It's just NumPy Some difficult problems in , If you want to learn more systematically NumPy And know the analysis process and answers of the above thinking questions , Please move to our knowledge planet !

 

Next up :Python library Scipy Advanced applications for

 

There are three AI Programming and open source framework knowledge

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

There are three AI Programming and open source framework knowledge planet created , Welcome to join , I hope you can use this platform , Have a solid programming foundation .

 

watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=

 

版权声明
本文为[There are three words]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/08/20210809154027111t.html

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database