python包numpy
NumPy (pronounced "numb pie") is one of the most important packages to grasp when you’re starting to learn Python.
NumPy(讀作“麻木派”)是您開始學習Python時要掌握的最重要的軟件包之一。
The package is known for a very useful data structure called the NumPy array. NumPy also allows Python developers to quickly perform a wide variety of numerical computations.
該程序包以一種非常有用的數據結構(稱為NumPy數組)而聞名。 NumPy還允許Python開發人員快速執行各種數值計算。
This tutorial will teach you the fundamentals of NumPy that you can use to build numerical Python applications today.
本教程將教您NumPy的基礎知識,您現在可以使用它們來構建數字Python應用程序。
目錄 (Table of Contents)
You can skip to a specific section of this NumPy tutorial using the table of contents below:
您可以使用以下目錄跳到本NumPy教程的特定部分:
Introduction to NumPy
NumPy簡介
NumPy Arrays
NumPy數組
NumPy Methods and Operations
NumPy方法和操作
NumPy Indexing and Assignment
NumPy索引和分配
Final Thoughts & Special Offer
最后的想法和特別優惠
NumPy簡介 (Introduction to NumPy)
In this section, we will introduce the NumPy library in Python.
在本節中,我們將介紹Python中的NumPy庫 。
什么是NumPy? (What is NumPy?)
NumPy is a Python library for scientific computing. NumPy stand for Numerical Python. Here is the official description of the library from its website:
NumPy是用于科學計算的Python庫。 NumPy代表數值Python。 這是圖書館網站的官方描述:
“NumPy is the fundamental package for scientific computing with Python. It contains among other things:
“ NumPy是使用Python進行科學計算的基本軟件包。 它包含以下內容:
a powerful N-dimensional array object
強大的N維數組對象
sophisticated (broadcasting) functions
復雜的(廣播)功能
tools for integrating C/C++ and Fortran code
集成C / C ++和Fortran代碼的工具
useful linear algebra, Fourier transform, and random number capabilities
有用的線性代數,傅立葉變換和隨機數功能
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
除了其明顯的科學用途外,NumPy還可以用作通用數據的高效多維容器。 可以定義任意數據類型。 這使NumPy可以無縫,快速地與各種數據庫集成。
NumPy is licensed under the BSD license, enabling reuse with few restrictions.”
NumPy已獲得BSD許可證的許可 ,從而幾乎沒有限制地實現了重用。”
NumPy is such an important Python library that there are other libraries (including pandas) that are built entirely on NumPy.
NumPy是一個非常重要的Python庫,因此還有其他完全基于NumPy構建的庫(包括熊貓)。
NumPy的主要好處 (The Main Benefit of NumPy)
The main benefit of NumPy is that it allows for extremely fast data generation and handling. NumPy has its own built-in data structure called an array
which is similar to the normal Python list
, but can store and operate on data much more efficiently.
NumPy的主要優點是它允許非常快速地生成和處理數據。 NumPy有自己的內置數據結構,稱為array
,它與普通的Python list
相似,但可以更有效地存儲和處理數據。
我們將了解NumPy的內容 (What We Will Learn About NumPy)
Advanced Python practitioners will spend much more time working with pandas than they spend working with NumPy. Still, given that pandas is built on NumPy, it is important to understand the most important aspects of the NumPy library.
與Python相比,高級Python從業人員與熊貓工作的時間要多得多。 盡管如此,鑒于熊貓是建立在NumPy之上的,因此了解NumPy庫的最重要方面非常重要。
Over the next several sections, we will cover the following information about the NumPy library:
在接下來的幾節中,我們將介紹有關NumPy庫的以下信息:
- NumPy Arrays NumPy數組
- NumPy Indexing and Assignment NumPy索引和分配
- NumPy Methods and Operations NumPy方法和操作
繼續 (Moving On)
Let’s move on to learning about NumPy arrays, the core data structure that every NumPy practitioner must be familiar with.
讓我們繼續學習NumPy數組,這是每個NumPy從業人員都必須熟悉的核心數據結構。
NumPy數組 (NumPy Arrays)
In this section, we will be learning about NumPy arrays.
在本節中,我們將學習NumPy數組 。
什么是NumPy數組? (What Are NumPy Arrays?)
NumPy arrays are the main way to store data using the NumPy library. They are similar to normal lists in Python, but have the advantage of being faster and having more built-in methods.
NumPy數組是使用NumPy庫存儲數據的主要方法。 它們類似于Python中的普通列表,但是具有更快的速度和具有更多內置方法的優點。
NumPy arrays are created by calling the array()
method from the NumPy library. Within the method, you should pass in a list.
NumPy數組是通過從NumPy庫中調用array()
方法創建的。 在方法內,您應該傳遞一個列表。
An example of a basic NumPy array is shown below. Note that while I run the import numpy as np
statement at the start of this code block, it will be excluded from the other code blocks in this section for brevity’s sake.
基本NumPy數組的示例如下所示。 請注意,雖然我在此代碼塊的開頭運行import numpy as np
語句,但為簡潔起見,本部分的其他代碼塊中將其排除在外。
import numpy as npsample_list = [1, 2, 3]np.array(sample_list)
The last line of that code block will result in an output that looks like this.
該代碼塊的最后一行將導致輸出如下所示。
array([1,2,3])
The array()
wrapper indicates that this is no longer a normal Python list. Instead, it is a NumPy array.
array()
包裝器指示這不再是普通的Python列表。 相反,它是一個NumPy數組。
兩種不同類型的NumPy數組 (The Two Different Types of NumPy Arrays)
There are two different types of NumPy arrays: vectors and matrices.
NumPy數組有兩種不同類型:向量和矩陣。
Vectors are one-dimensional NumPy arrays, and look like this:
向量是一維NumPy數組,如下所示:
my_vector = np.array(['this', 'is', 'a', 'vector'])
Matrices are two-dimensional arrays and are created by passing a list of lists into the np.array()
method. An example is below.
矩陣是二維數組,通過將列表列表傳遞到np.array()
方法中來創建。 下面是一個示例。
my_matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]np.array(my_matrix)
You can also expand NumPy arrays to deal with three-, four-, five-, six- or higher-dimensional arrays, but they are rare and largely outside the scope of this course (after all, this is a course on Python programming, not linear algebra).
您還可以擴展NumPy數組以處理三維,四維,五維,六維或更高維的數組,但是它們很少見,并且在本課程的范圍之外(畢竟,這是有關Python編程的課程,不是線性代數)。
NumPy數組:內置方法 (NumPy Arrays: Built-In Methods)
NumPy arrays come with a number of useful built-in methods. We will spend the rest of this section discussing these methods in detail.
NumPy數組帶有許多有用的內置方法。 我們將在本節的其余部分中詳細討論這些方法。
如何使用NumPy在Python中獲取一系列數字 (How To Get A Range Of Numbers in Python Using NumPy)
NumPy has a useful method called arange
that takes in two numbers and gives you an array of integers that are greater than or equal to (>=
) the first number and less than (<
) the second number.
NumPy有一個有用的方法,稱為arange
,它接受兩個數字,并為您提供一個大于或等于第一個數字( >=
)且小于第二個數字( <
)的整數數組。
An example of the arange
method is below.
下面是arange
方法的示例。
np.arange(0,5)#Returns array([0, 1, 2, 3, 4])
You can also include a third variable in the arange
method that provides a step-size for the function to return. Passing in 2
as the third variable will return every 2nd number in the range, passing in 5
as the third variable will return every 5th number in the range, and so on.
您還可以在arange
方法中包含第三個變量,該變量為函數返回提供了步長。 傳入2
作為第三個變量將返回該范圍內的每個第二個數字,傳入5
作為第三個變量將返回該范圍內每個第5個的數字,依此類推。
An example of using the third variable in the arange
method is below.
下面是在arange
方法中使用第三個變量的示例。
np.arange(1,11,2)#Returns array([1, 3, 5, 7, 9])
如何使用NumPy在Python中生成一個和零 (How To Generates Ones and Zeros in Python Using NumPy)
While programming, you will from time to time need to create arrays of ones or zeros. NumPy has built-in methods that allow you to do either of these.
在編程時,您將不時需要創建一個由1或0組成的數組。 NumPy具有內置方法,可讓您執行上述任何一種操作。
We can create arrays of zeros using NumPy’s zeros
method. You pass in the number of integers you’d like to create as the argument of the function. An example is below.
我們可以使用NumPy的zeros
方法創建零數組。 您傳入要創建的整數數量作為函數的參數。 下面是一個示例。
np.zeros(4)#Returns array([0, 0, 0, 0])
You can also do something similar using three-dimensional arrays. For example, np.zeros(5, 5)
creates a 5x5 matrix that contains all zeros.
您也可以使用三維數組執行類似的操作。 例如, np.zeros(5, 5)
創建一個包含所有零的5x5矩陣。
We can create arrays of ones using a similar method named ones
. An example is below.
我們可以使用類似的方法來創建一個數組ones
。 下面是一個示例。
np.ones(5)#Returns array([1, 1, 1, 1, 1])
如何使用NumPy在Python中均勻劃分數字范圍 (How To Evenly Divide A Range Of Numbers In Python Using NumPy)
There are many situations in which you have a range of numbers and you would like to equally divide that range of numbers into intervals. NumPy’s linspace
method is designed to solve this problem. linspace
takes in three arguments:
在許多情況下,您擁有一定范圍的數字,并且您希望將該數字范圍平均劃分為一些區間。 NumPy的linspace
方法旨在解決此問題。 linspace
接受三個參數:
- The start of the interval 間隔的開始
- The end of the interval 間隔結束
- The number of subintervals that you’d like the interval to be divided into 您希望將間隔劃分為的子間隔數
An example of the linspace
method is below.
下面是linspace
方法的示例。
np.linspace(0, 1, 10)#Returns array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
如何使用NumPy在Python中創建身份矩陣 (How To Create An Identity Matrix In Python Using NumPy)
Anyone who has studied linear algebra will be familiar with the concept of an ‘identity matrix’, which is a square matrix whose diagonal values are all 1
. NumPy has a built-in function that takes in one argument for building identity matrices. The function is eye
.
任何學習過線性代數的人都將熟悉“恒等矩陣”的概念,該矩陣是對角線均為1
的方矩陣。 NumPy具有一個內置函數,該函數接受一個用于構建身份矩陣的參數。 功能是eye
。
Examples are below:
示例如下:
np.eye(1)#Returns a 1x1 identity matrixnp.eye(2) #Returns a 2x2 identity matrixnp.eye(50)#Returns a 50x50 identity matrix
如何使用NumPy在Python中創建隨機數 (How To Create Random Numbers in Python Using NumPy)
NumPy has a number of methods built-in that allow you to create arrays of random numbers. Each of these methods starts with random
. A few examples are below:
NumPy具有許多內置方法,可讓您創建隨機數數組。 這些方法中的每一個都從random
開始。 以下是一些示例:
np.random.rand(sample_size)#Returns a sample of random numbers between 0 and 1.#Sample size can either be one integer (for a one-dimensional array) or two integers separated by commas (for a two-dimensional array).np.random.randn(sample_size)#Returns a sample of random numbers between 0 and 1, following the normal distribution.#Sample size can either be one integer (for a one-dimensional array) or two integers separated by commas (for a two-dimensional array).np.random.randint(low, high, sample_size)#Returns a sample of integers that are greater than or equal to 'low' and less than 'high'
如何重塑NumPy數組 (How To Reshape NumPy Arrays)
It is very common to take an array with certain dimensions and transform that array into a different shape. For example, you might have a one-dimensional array with 10 elements and want to switch it to a 2x5 two-dimensional array.
拍攝具有特定尺寸的數組并將該數組轉換為其他形狀是很常見的。 例如,您可能有一個包含10個元素的一維數組,并且想要將其切換為2x5二維數組。
An example is below:
下面是一個示例:
arr = np.array([0,1,2,3,4,5])arr.reshape(2,3)
The output of this operation is:
該操作的輸出為:
array([[0, 1, 2],[3, 4, 5]])
Note that in order to use the reshape
method, the original array must have the same number of elements as the array that you’re trying to reshape it into.
請注意,為了使用reshape
方法,原始數組必須具有與您想要對其進行整形的數組相同數量的元素。
If you’re curious about the current shape of a NumPy array, you can determine its shape using NumPy’s shape
attribute. Using our previous arr
variable structure, an example of how to call the shape
attribute is below:
如果您對NumPy數組的當前形狀感到好奇,則可以使用NumPy的shape
屬性確定其形狀。 使用我們以前的arr
變量結構,下面是一個如何調用shape
屬性的示例:
arr = np.array([0,1,2,3,4,5])arr.shape#Returns (6,) - note that there is no second element since it is a one-dimensional arrayarr = arr.reshape(2,3)arr.shape#Returns (2,3)
You can also combine the reshape
method with the shape
attribute on one line like this:
您還可以在一行上將reshape
方法與shape
屬性結合使用,如下所示:
arr.reshape(2,3).shape#Returns (2,3)
如何找到NumPy數組的最大值和最小值 (How To Find The Maximum and Minimum Value Of A NumPy Array)
To conclude this section, let’s learn about four useful methods for identifying the maximum and minimum values within a NumPy array. We’ll be working with this array:
總結本節,讓我們了解四種用于識別NumPy數組中的最大值和最小值的有用方法。 我們將使用此數組:
simple_array = [1, 2, 3, 4]
We can use the max
method to find the maximum value of a NumPy array. An example is below.
我們可以使用max
方法來找到NumPy數組的最大值。 下面是一個示例。
simple_array.max()#Returns 4
We can also use the argmax
method to find the index of the maximum value within a NumPy array. This is useful for when you want to find the location of the maximum value but you do not necessarily care what its value is.
我們還可以使用argmax
方法在NumPy數組中找到最大值的索引。 當您要查找最大值的位置但不必關心其值是什么時,這很有用。
An example is below.
下面是一個示例。
simple_array.argmax()#Returns 3
Similarly, we can use the min
and argmin
methods to find the value and index of the minimum value within a NumPy array.
類似地,我們可以使用min
和argmin
方法在NumPy數組中查找最小值的值和索引。
simple_array.min()#Returns 1simple_array.argmin()#Returns 0
繼續 (Moving On)
In this section, we discussed various attributes and methods of NumPy arrays. We will follow up by working through some NumPy array practice problems in the next section.
在本節中,我們討論了NumPy數組的各種屬性和方法。 在下一節中,我們將繼續解決一些NumPy數組實踐問題。
NumPy方法和操作 (NumPy Methods and Operations)
In this section, we will be working through various operations included in the NumPy library.
在本節中,我們將研究NumPy庫中包含的各種操作。
Throughout this section, we will be assuming that the import numpy as np
command has already been run.
在本節中,我們假設已經運行import numpy as np
命令。
本節中使用的數組 (The Array Used In This Section)
For this section, I will be working with an array of length 4 created using np.arange
in all of the examples.
在本節中,我將使用在所有示例中使用np.arange
創建的長度為4的數組。
If you’d like to compare my array with the outputs used in this section, here is how I created and printed the array:
如果您想將我的數組與本節中使用的輸出進行比較,這是我創建和打印數組的方式:
arr = np.arange(4)arr
The array values are below.
數組值如下。
array([0, 1, 2, 3])
如何在Python中使用數字執行算術運算 (How To Perform Arithmetic In Python Using Number)
NumPy makes it very easy to perform arithmetic with arrays. You can either perform arithmetic using the array and a single number, or you can perform arithmetic between two NumPy arrays.
NumPy使對數組執行算術變得非常容易。 您可以使用數組和單個數字執行算術運算,也可以在兩個NumPy數組之間執行算術運算。
We explore each of the major mathematical operations below.
我們在下面探索每個主要的數學運算。
加成 (Addition)
When adding a single number to a NumPy array, that number is added to each element in the array. An example is below:
將單個數字添加到NumPy數組時,該數字將添加到數組中的每個元素。 下面是一個示例:
2 + arr#Returns array([2, 3, 4, 5])
You can add two NumPy arrays using the +
operator. The arrays are added on an element-by-element basis (meaning the first elements are added together, the second elements are added together, and so on).
您可以使用+
運算符添加兩個NumPy數組。 數組是在逐個元素的基礎上添加的(意味著將第一個元素添加在一起,將第二個元素添加在一起,依此類推)。
An example is below.
下面是一個示例。
arr + arr#Returns array([0, 2, 4, 6])
減法 (Subtraction)
Like addition, subtraction is performed on an element-by-element basis for NumPy arrays. You can find example for both a single number and another NumPy array below.
像加法一樣,對于NumPy數組,在逐個元素的基礎上執行減法。 您可以在下面找到單個數字和另一個NumPy數組的示例。
arr - 10#Returns array([-10, -9, -8, -7])arr - arr#Returns array([0, 0, 0, 0])
乘法 (Multiplication)
Multiplication is also performed on an element-by-element basis for both single numbers and NumPy arrays.
對于單個數字和NumPy數組,也逐個元素地進行乘法。
Two examples are below.
下面是兩個示例。
6 * arr#Returns array([ 0, 6, 12, 18])arr * arr#Returns array([0, 1, 4, 9])
師 (Division)
By this point, you’re probably not surprised to learn that division performed on NumPy arrays is done on an element-by-element basis. An example of dividing arr
by a single number is below:
至此,您可能不驚奇得知在NumPy數組上執行的除法是在逐個元素的基礎上完成的。 下面是將arr
除以一個數字的示例:
arr / 2#Returns array([0. , 0.5, 1. , 1.5])
Division does have one notable exception compared to the other mathematical operations we have seen in this section. Since we cannot divide by zero, doing so will cause the corresponding field to be populated by a nan
value, which is Python shorthand for “Not A Number”. Jupyter Notebook will also print a warning that looks like this:
與本節中所見的其他數學運算相比,除法確實有一個明顯的例外。 由于我們無法將其除以零,因此將導致用nan
值填充相應的字段,該值是Python的“ Not A Number”的縮寫。 Jupyter Notebook還將打印如下警告:
RuntimeWarning: invalid value encountered in true_divide
An example of dividing by zero is with a NumPy array is shown below.
NumPy數組除以零的示例如下所示。
arr / arr#Returns array([nan, 1., 1., 1.])
We will learn how to deal with nan
values in more detail later in this course.
在本課程的后面,我們將詳細學習如何處理nan
值。
NumPy數組中的復雜操作 (Complex Operations in NumPy Arrays)
Many operations cannot simply be performed by applying the normal syntax to a NumPy array. In this section, we will explore several mathematical operations that have built-in methods in the NumPy library.
不能簡單地通過將常規語法應用于NumPy數組來執行許多操作。 在本節中,我們將探討NumPy庫中具有內置方法的幾種數學運算。
如何使用NumPy計算平方根 (How To Calculate Square Roots Using NumPy)
You can calculate the square root of every element in an array using the np.sqrt
method:
您可以使用np.sqrt
方法計算數組中每個元素的np.sqrt
:
np.sqrt(arr)#Returns array([0., 1., 1.41421356, 1.73205081])
Many other examples are below (note that you will not be tested on these, but it is still useful to see the capabilities of NumPy):
以下是許多其他示例(請注意,您將不會在其中進行測試,但查看NumPy的功能仍然很有用):
np.exp(arr)#Returns e^element for every element in the arraynp.sin(arr)#Calculate the trigonometric sine of every value in the arraynp.cos(arr)#Calculate the trigonometric cosine of every value in the arraynp.log(arr)#Calculate the base-ten logarithm of every value in the array
繼續 (Moving On)
In this section, we explored the various methods and operations available in the NumPy Python library. We will text your knowledge of these concepts in the practice problems presented next.
在本節中,我們探索了NumPy Python庫中可用的各種方法和操作。 我們將在下一個練習題中將您對這些概念的知識發短信。
NumPy索引和分配 (NumPy Indexing and Assignment)
In this section, we will explore indexing and assignment in NumPy arrays.
在本節中,我們將探討NumPy數組中的索引編制和賦值。
我將在本節中使用的數組 (The Array I’ll Be Using In This Section)
As before, I will be using a specific array through this section. This time it will be generated using the np.random.rand
method. Here’s how I generated the array:
和以前一樣,我將在本節中使用特定的數組。 這次將使用np.random.rand
方法生成它。 這是我生成數組的方式:
arr = np.random.rand(5)
Here is the actual array:
這是實際的數組:
array([0.69292946, 0.9365295 , 0.65682359, 0.72770856, 0.83268616])
To make this array easier to look at, I will round every element of the array to 2 decimal places using NumPy’s round
method:
為了使該數組更易于查看,我將使用NumPy的round
方法將數組的每個元素四舍五入到小數點后兩位:
arr = np.round(arr, 2)
Here’s the new array:
這是新的數組:
array([0.69, 0.94, 0.66, 0.73, 0.83])
如何從NumPy數組返回特定??元素 (How To Return A Specific Element From A NumPy Array)
We can select (and return) a specific element from a NumPy array in the same way that we could using a normal Python list: using square brackets.
我們可以像使用普通的Python列表一樣,從NumPy數組中選擇(并返回)特定元素:使用方括號。
An example is below:
下面是一個示例:
arr[0]#Returns 0.69
We can also reference multiple elements of a NumPy array using the colon operator. For example, the index [2:]
selects every element from index 2 onwards. The index [:3]
selects every element up to and excluding index 3. The index [2:4]
returns every element from index 2 to index 4, excluding index 4. The higher endpoint is always excluded.
我們還可以使用冒號運算符引用NumPy數組的多個元素。 例如,索引[2:]
從索引2開始選擇每個元素。 索引[:3]
選擇直到索引3的每個元素,但不包括索引3。索引[2:4]
返回從索引2到索引4的每個元素,但不包括索引4。始終排除較高的端點。
A few example of indexing using the colon operator are below.
下面是使用冒號運算符建立索引的一些示例。
arr[:]#Returns the entire array: array([0.69, 0.94, 0.66, 0.73, 0.83])arr[1:]#Returns array([0.94, 0.66, 0.73, 0.83])arr[1:4] #Returns array([0.94, 0.66, 0.73])
NumPy數組中的元素分配 (Element Assignment in NumPy Arrays)
We can assign new values to an element of a NumPy array using the =
operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).
我們可以使用=
運算符將新值分配給NumPy數組的元素,就像常規的python列表一樣。 下面是幾個示例(請注意,這都是一個代碼塊,這意味著元素分配是逐步進行的)。
array([0.12, 0.94, 0.66, 0.73, 0.83])arr#Returns array([0.12, 0.94, 0.66, 0.73, 0.83])arr[:] = 0arr#Returns array([0., 0., 0., 0., 0.])arr[2:5] = 0.5arr#Returns array([0. , 0. , 0.5, 0.5, 0.5])
NumPy中的數組引用 (Array Referencing in NumPy)
NumPy makes use of a concept called ‘array referencing’ which is a very common source of confusion for people that are new to the library.
NumPy使用了一個稱為“數組引用”的概念,這對于圖書館新手來說是一個很常見的困惑源。
To understand array referencing, let’s first consider an example:
為了理解數組引用,我們首先考慮一個示例:
new_array = np.array([6, 7, 8, 9])second_new_array = new_array[0:2]second_new_array#Returns array([6, 7])second_new_array[1] = 4second_new_array #Returns array([6, 4]), as expectednew_array #Returns array([6, 4, 8, 9]) #which is DIFFERENT from its original value of array([6, 7, 8, 9])#What the heck?
As you can see, modifying second_new_array
also changed the value of new_array
.
正如你所看到的,修改second_new_array
也改變了價值new_array
。
Why is this?
為什么是這樣?
By default, NumPy does not create a copy of an array when you reference the original array variable using the =
assignment operator. Instead, it simply points the new variable to the old variable, which allows the second variable to make modification to the original variable - even if this is not your intention.
默認情況下,當您使用=
賦值運算符引用原始數組變量時,NumPy不會創建數組的副本。 相反,它只是將新變量指向舊變量,這允許第二個變量對原始變量進行修改-即使這不是您的意圖。
This may seem bizarre, but it does have a logical explanation. The purpose of array referencing is to conserve computing power. When working with large data sets, you would quickly run out of RAM if you created a new array every time you wanted to work with a slice of the array.
這可能看起來很奇怪,但是確實有一個合理的解釋。 數組引用的目的是節省計算能力。 使用大型數據集時,如果每次要使用陣列的一部分時都創建了一個新的陣列,則會很快用完RAM。
Fortunately, there is a workaround to array referencing. You can use the copy
method to explicitly copy a NumPy array.
幸運的是,有一種解決數組引用的方法。 您可以使用copy
方法顯式復制NumPy數組。
An example of this is below.
下面是一個示例。
array_to_copy = np.array([1, 2, 3])copied_array = array_to_copy.copy()array_to_copy#Returns array([1, 2, 3])copied_array#Returns array([1, 2, 3])
As you can see below, making modifications to the copied array does not alter the original.
如下所示,對復制的數組進行修改不會更改原始數組。
copied_array[0] = 9copied_array#Returns array([9, 2, 3])array_to_copy#Returns array([1, 2, 3])
So far in the section, we have only explored how to reference one-dimensional NumPy arrays. We will now explore the indexing of two-dimensional arrays.
到目前為止,在本節中,我們僅探討了如何引用一維NumPy數組。 現在,我們將探討二維數組的索引。
索引二維NumPy數組 (Indexing Two-Dimensional NumPy Arrays)
To start, let’s create a two-dimensional NumPy array named mat
:
首先,讓我們創建一個名為mat
的二維NumPy數組:
mat = np.array([[5, 10, 15],[20, 25, 30],[35, 40, 45]])mat"""Returns:array([[ 5, 10, 15],[20, 25, 30],[35, 40, 45]])"""
There are two ways to index a two-dimensional NumPy array:
索引二維NumPy數組有兩種方法:
mat[row, col]
mat[row, col]
mat[row][col]
mat[row][col]
I personally prefer to index using the mat[row][col]
nomenclature because it is easier to visualize in a step-by-step fashion. For example:
我個人更喜歡使用mat[row][col]
命名法進行索引,因為它更易于逐步顯示。 例如:
#First, let's get the first row:mat[0]#Next, let's get the last element of the first row:mat[0][-1]
You can also generate sub-matrices from a two-dimensional NumPy array using this notation:
您還可以使用以下符號從二維NumPy數組生成子矩陣:
mat[1:][:2]"""Returns:array([[20, 25, 30],[35, 40, 45]])"""
Array referencing also applies to two-dimensional arrays in NumPy, so be sure to use the copy
method if you want to avoid inadvertently modifying an original array after saving a slice of it into a new variable name.
數組引用也適用于NumPy中的二維數組,因此,如果要避免在將原始數組的一部分保存為新變量名后避免無意間修改原始數組,請務必使用copy
方法。
使用NumPy數組進行條件選擇 (Conditional Selection Using NumPy Arrays)
NumPy arrays support a feature called conditional selection
, which allows you to generate a new array of boolean values that state whether each element within the array satisfies a particular if
statement.
NumPy數組支持稱為conditional selection
的功能,該功能使您可以生成一個新的布爾值數組,該值指示數組中的每個元素是否滿足特定的if
語句。
An example of this is below (I also re-created our original arr
variable since its been awhile since we’ve seen it):
下面是一個示例(自從我們看到它以來已經有一段時間了,我還重新創建了我們的原始arr
變量):
arr = np.array([0.69, 0.94, 0.66, 0.73, 0.83])arr > 0.7#Returns array([False, True, False, True, True])
You can also generate a new array of values that satisfy this condition by passing the condition into the square brackets (just like we do for indexing).
您也可以通過將條件傳遞到方括號中來生成滿足該條件的新值數組(就像我們對索引所做的一樣)。
An example of this is below:
下面是一個示例:
arr[arr > 0.7]#Returns array([0.94, 0.73, 0.83])
Conditional selection can become significantly more complex than this. We will explore more examples in this section’s associated practice problems.
有條件的選擇會比這復雜得多。 我們將在本節的相關實踐問題中探索更多示例。
繼續 (Moving On)
In this section, we explored NumPy array indexing and assignment in thorough detail. We will solidify your knowledge of these concepts further by working through a batch of practice problems in the next section.
在本節中,我們將詳細探討NumPy數組的索引和賦值。 在下一部分中,我們將通過解決一系列實踐問題來進一步鞏固您對這些概念的了解。
最后的想法和特別優惠 (Final Thoughts & Special Offer)
Thanks for reading this article on NumPy, which is one of my favorite Python packages and a must-know library for every Python developer.
感謝您在NumPy上閱讀本文,這是我最喜歡的Python軟件包之一,也是每個Python開發人員都必須知道的庫。
This tutorial is an excerpt from my course Python For Finance and Data Science. If you're interested in learning more core Python skills, the course is 50% off for the first 50 freeCodeCamp readers that sign up - click here to get your discounted course now!
本教程摘錄自我的課程 Python For Finance and Data Science 。 如果您有興趣學習更多Python核心技能,那么注冊的前50位freeCodeCamp讀者均可享受該課程50%的折扣- 單擊此處立即獲得折扣課程 !
翻譯自: https://www.freecodecamp.org/news/the-ultimate-guide-to-the-numpy-scientific-computing-library-for-python/
python包numpy