python包numpy_NumPy Python科学计算软件包的终极指南
python包numpy
NumPy (pronounced "numb pie") is one of the most important packages to grasp when you’re starting to learn Python.
NumPy(讀作“麻木派”)是您開始學(xué)習(xí)Python時(shí)要掌握的最重要的軟件包之一。
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.
該程序包以一種非常有用的數(shù)據(jù)結(jié)構(gòu)(稱為NumPy數(shù)組)而聞名。 NumPy還允許Python開發(fā)人員快速執(zhí)行各種數(shù)值計(jì)算。
This tutorial will teach you the fundamentals of NumPy that you can use to build numerical Python applications today.
本教程將教您NumPy的基礎(chǔ)知識(shí),您現(xiàn)在可以使用它們來構(gòu)建數(shù)字Python應(yīng)用程序。
目錄 (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數(shù)組
NumPy Methods and Operations
NumPy方法和操作
NumPy Indexing and Assignment
NumPy索引和分配
Final Thoughts & Special Offer
最后的想法和特別優(yōu)惠
NumPy簡介 (Introduction to NumPy)
In this section, we will introduce the NumPy library in Python.
在本節(jié)中,我們將介紹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是用于科學(xué)計(jì)算的Python庫。 NumPy代表數(shù)值Python。 這是圖書館網(wǎng)站的官方描述:
“NumPy is the fundamental package for scientific computing with Python. It contains among other things:
“ NumPy是使用Python進(jìn)行科學(xué)計(jì)算的基本軟件包。 它包含以下內(nèi)容:
a powerful N-dimensional array object
強(qiáng)大的N維數(shù)組對(duì)象
sophisticated (broadcasting) functions
復(fù)雜的(廣播)功能
tools for integrating C/C++ and Fortran code
集成C / C ++和Fortran代碼的工具
useful linear algebra, Fourier transform, and random number capabilities
有用的線性代數(shù),傅立葉變換和隨機(jī)數(shù)功能
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.
除了其明顯的科學(xué)用途外,NumPy還可以用作通用數(shù)據(jù)的高效多維容器。 可以定義任意數(shù)據(jù)類型。 這使NumPy可以無縫,快速地與各種數(shù)據(jù)庫集成。
NumPy is licensed under the BSD license, enabling reuse with few restrictions.”
NumPy已獲得BSD許可證的許可 ,從而幾乎沒有限制地實(shí)現(xiàn)了重用。”
NumPy is such an important Python library that there are other libraries (including pandas) that are built entirely on NumPy.
NumPy是一個(gè)非常重要的Python庫,因此還有其他完全基于NumPy構(gòu)建的庫(包括熊貓)。
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的主要優(yōu)點(diǎn)是它允許非常快速地生成和處理數(shù)據(jù)。 NumPy有自己的內(nèi)置數(shù)據(jù)結(jié)構(gòu),稱為array ,它與普通的Python list相似,但可以更有效地存儲(chǔ)和處理數(shù)據(jù)。
我們將了解NumPy的內(nèi)容 (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相比,高級(jí)Python從業(yè)人員與熊貓工作的時(shí)間要多得多。 盡管如此,鑒于熊貓是建立在NumPy之上的,因此了解NumPy庫的最重要方面非常重要。
Over the next several sections, we will cover the following information about the NumPy library:
在接下來的幾節(jié)中,我們將介紹有關(guān)NumPy庫的以下信息:
- NumPy Arrays NumPy數(shù)組
- NumPy Indexing and Assignment NumPy索引和分配
- NumPy Methods and Operations NumPy方法和操作
繼續(xù) (Moving On)
Let’s move on to learning about NumPy arrays, the core data structure that every NumPy practitioner must be familiar with.
讓我們繼續(xù)學(xué)習(xí)NumPy數(shù)組,這是每個(gè)NumPy從業(yè)人員都必須熟悉的核心數(shù)據(jù)結(jié)構(gòu)。
NumPy數(shù)組 (NumPy Arrays)
In this section, we will be learning about NumPy arrays.
在本節(jié)中,我們將學(xué)習(xí)NumPy數(shù)組 。
什么是NumPy數(shù)組? (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數(shù)組是使用NumPy庫存儲(chǔ)數(shù)據(jù)的主要方法。 它們類似于Python中的普通列表,但是具有更快的速度和具有更多內(nèi)置方法的優(yōu)點(diǎn)。
NumPy arrays are created by calling the array() method from the NumPy library. Within the method, you should pass in a list.
NumPy數(shù)組是通過從NumPy庫中調(diào)用array()方法創(chuàng)建的。 在方法內(nèi),您應(yīng)該傳遞一個(gè)列表。
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數(shù)組的示例如下所示。 請(qǐng)注意,雖然我在此代碼塊的開頭運(yùn)行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.
該代碼塊的最后一行將導(dǎo)致輸出如下所示。
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列表。 相反,它是一個(gè)NumPy數(shù)組。
兩種不同類型的NumPy數(shù)組 (The Two Different Types of NumPy Arrays)
There are two different types of NumPy arrays: vectors and matrices.
NumPy數(shù)組有兩種不同類型:向量和矩陣。
Vectors are one-dimensional NumPy arrays, and look like this:
向量是一維NumPy數(shù)組,如下所示:
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.
矩陣是二維數(shù)組,通過將列表列表傳遞到np.array()方法中來創(chuàng)建。 下面是一個(gè)示例。
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).
您還可以擴(kuò)展NumPy數(shù)組以處理三維,四維,五維,六維或更高維的數(shù)組,但是它們很少見,并且在本課程的范圍之外(畢竟,這是有關(guān)Python編程的課程,不是線性代數(shù))。
NumPy數(shù)組:內(nèi)置方法 (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數(shù)組帶有許多有用的內(nèi)置方法。 我們將在本節(jié)的其余部分中詳細(xì)討論這些方法。
如何使用NumPy在Python中獲取一系列數(shù)字 (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有一個(gè)有用的方法,稱為arange ,它接受兩個(gè)數(shù)字,并為您提供一個(gè)大于或等于第一個(gè)數(shù)字( >= )且小于第二個(gè)數(shù)字( < )的整數(shù)數(shù)組。
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方法中包含第三個(gè)變量,該變量為函數(shù)返回提供了步長。 傳入2作為第三個(gè)變量將返回該范圍內(nèi)的每個(gè)第二個(gè)數(shù)字,傳入5作為第三個(gè)變量將返回該范圍內(nèi)每個(gè)第5個(gè)的數(shù)字,依此類推。
An example of using the third variable in the arange method is below.
下面是在arange方法中使用第三個(gè)變量的示例。
np.arange(1,11,2)#Returns array([1, 3, 5, 7, 9])如何使用NumPy在Python中生成一個(gè)和零 (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.
在編程時(shí),您將不時(shí)需要?jiǎng)?chuàng)建一個(gè)由1或0組成的數(shù)組。 NumPy具有內(nèi)置方法,可讓您執(zhí)行上述任何一種操作。
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方法創(chuàng)建零數(shù)組。 您傳入要?jiǎng)?chuàng)建的整數(shù)數(shù)量作為函數(shù)的參數(shù)。 下面是一個(gè)示例。
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.
您也可以使用三維數(shù)組執(zhí)行類似的操作。 例如, np.zeros(5, 5)創(chuàng)建一個(gè)包含所有零的5x5矩陣。
We can create arrays of ones using a similar method named ones. An example is below.
我們可以使用類似的方法來創(chuàng)建一個(gè)數(shù)組ones 。 下面是一個(gè)示例。
np.ones(5)#Returns array([1, 1, 1, 1, 1])如何使用NumPy在Python中均勻劃分?jǐn)?shù)字范圍 (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:
在許多情況下,您擁有一定范圍的數(shù)字,并且您希望將該數(shù)字范圍平均劃分為一些區(qū)間。 NumPy的linspace方法旨在解決此問題。 linspace接受三個(gè)參數(shù):
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中創(chuàng)建身份矩陣 (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.
任何學(xué)習(xí)過線性代數(shù)的人都將熟悉“恒等矩陣”的概念,該矩陣是對(duì)角線均為1的方矩陣。 NumPy具有一個(gè)內(nèi)置函數(shù),該函數(shù)接受一個(gè)用于構(gòu)建身份矩陣的參數(shù)。 功能是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中創(chuàng)建隨機(jī)數(shù) (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具有許多內(nèi)置方法,可讓您創(chuàng)建隨機(jī)數(shù)數(shù)組。 這些方法中的每一個(gè)都從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數(shù)組 (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.
拍攝具有特定尺寸的數(shù)組并將該數(shù)組轉(zhuǎn)換為其他形狀是很常見的。 例如,您可能有一個(gè)包含10個(gè)元素的一維數(shù)組,并且想要將其切換為2x5二維數(shù)組。
An example is below:
下面是一個(gè)示例:
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.
請(qǐng)注意,為了使用reshape方法,原始數(shù)組必須具有與您想要對(duì)其進(jìn)行整形的數(shù)組相同數(shù)量的元素。
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:
如果您對(duì)NumPy數(shù)組的當(dāng)前形狀感到好奇,則可以使用NumPy的shape屬性確定其形狀。 使用我們以前的arr變量結(jié)構(gòu),下面是一個(gè)如何調(diào)用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屬性結(jié)合使用,如下所示:
arr.reshape(2,3).shape#Returns (2,3)如何找到NumPy數(shù)組的最大值和最小值 (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:
總結(jié)本節(jié),讓我們了解四種用于識(shí)別NumPy數(shù)組中的最大值和最小值的有用方法。 我們將使用此數(shù)組:
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數(shù)組的最大值。 下面是一個(gè)示例。
simple_array.max()#Returns 4We 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數(shù)組中找到最大值的索引。 當(dāng)您要查找最大值的位置但不必關(guān)心其值是什么時(shí),這很有用。
An example is below.
下面是一個(gè)示例。
simple_array.argmax()#Returns 3Similarly, 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數(shù)組中查找最小值的值和索引。
simple_array.min()#Returns 1simple_array.argmin()#Returns 0繼續(xù) (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.
在本節(jié)中,我們討論了NumPy數(shù)組的各種屬性和方法。 在下一節(jié)中,我們將繼續(xù)解決一些NumPy數(shù)組實(shí)踐問題。
NumPy方法和操作 (NumPy Methods and Operations)
In this section, we will be working through various operations included in the NumPy library.
在本節(jié)中,我們將研究NumPy庫中包含的各種操作。
Throughout this section, we will be assuming that the import numpy as np command has already been run.
在本節(jié)中,我們假設(shè)已經(jīng)運(yùn)行import numpy as np命令。
本節(jié)中使用的數(shù)組 (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.
在本節(jié)中,我將使用在所有示例中使用np.arange創(chuàng)建的長度為4的數(shù)組。
If you’d like to compare my array with the outputs used in this section, here is how I created and printed the array:
如果您想將我的數(shù)組與本節(jié)中使用的輸出進(jìn)行比較,這是我創(chuàng)建和打印數(shù)組的方式:
arr = np.arange(4)arrThe array values are below.
數(shù)組值如下。
array([0, 1, 2, 3])如何在Python中使用數(shù)字執(zhí)行算術(shù)運(yùn)算 (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使對(duì)數(shù)組執(zhí)行算術(shù)變得非常容易。 您可以使用數(shù)組和單個(gè)數(shù)字執(zhí)行算術(shù)運(yùn)算,也可以在兩個(gè)NumPy數(shù)組之間執(zhí)行算術(shù)運(yùn)算。
We explore each of the major mathematical operations below.
我們在下面探索每個(gè)主要的數(shù)學(xué)運(yùn)算。
加成 (Addition)
When adding a single number to a NumPy array, that number is added to each element in the array. An example is below:
將單個(gè)數(shù)字添加到NumPy數(shù)組時(shí),該數(shù)字將添加到數(shù)組中的每個(gè)元素。 下面是一個(gè)示例:
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).
您可以使用+運(yùn)算符添加兩個(gè)NumPy數(shù)組。 數(shù)組是在逐個(gè)元素的基礎(chǔ)上添加的(意味著將第一個(gè)元素添加在一起,將第二個(gè)元素添加在一起,依此類推)。
An example is below.
下面是一個(gè)示例。
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.
像加法一樣,對(duì)于NumPy數(shù)組,在逐個(gè)元素的基礎(chǔ)上執(zhí)行減法。 您可以在下面找到單個(gè)數(shù)字和另一個(gè)NumPy數(shù)組的示例。
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.
對(duì)于單個(gè)數(shù)字和NumPy數(shù)組,也逐個(gè)元素地進(jìn)行乘法。
Two examples are below.
下面是兩個(gè)示例。
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數(shù)組上執(zhí)行的除法是在逐個(gè)元素的基礎(chǔ)上完成的。 下面是將arr除以一個(gè)數(shù)字的示例:
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:
與本節(jié)中所見的其他數(shù)學(xué)運(yùn)算相比,除法確實(shí)有一個(gè)明顯的例外。 由于我們無法將其除以零,因此將導(dǎo)致用nan值填充相應(yīng)的字段,該值是Python的“ Not A Number”的縮寫。 Jupyter Notebook還將打印如下警告:
RuntimeWarning: invalid value encountered in true_divideAn example of dividing by zero is with a NumPy array is shown below.
NumPy數(shù)組除以零的示例如下所示。
arr / arr#Returns array([nan, 1., 1., 1.])We will learn how to deal with nan values in more detail later in this course.
在本課程的后面,我們將詳細(xì)學(xué)習(xí)如何處理nan值。
NumPy數(shù)組中的復(fù)雜操作 (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.
不能簡單地通過將常規(guī)語法應(yīng)用于NumPy數(shù)組來執(zhí)行許多操作。 在本節(jié)中,我們將探討NumPy庫中具有內(nèi)置方法的幾種數(shù)學(xué)運(yùn)算。
如何使用NumPy計(jì)算平方根 (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方法計(jì)算數(shù)組中每個(gè)元素的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):
以下是許多其他示例(請(qǐng)注意,您將不會(huì)在其中進(jìn)行測試,但查看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繼續(xù) (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.
在本節(jié)中,我們探索了NumPy Python庫中可用的各種方法和操作。 我們將在下一個(gè)練習(xí)題中將您對(duì)這些概念的知識(shí)發(fā)短信。
NumPy索引和分配 (NumPy Indexing and Assignment)
In this section, we will explore indexing and assignment in NumPy arrays.
在本節(jié)中,我們將探討NumPy數(shù)組中的索引編制和賦值。
我將在本節(jié)中使用的數(shù)組 (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:
和以前一樣,我將在本節(jié)中使用特定的數(shù)組。 這次將使用np.random.rand方法生成它。 這是我生成數(shù)組的方式:
arr = np.random.rand(5)Here is the actual array:
這是實(shí)際的數(shù)組:
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:
為了使該數(shù)組更易于查看,我將使用NumPy的round方法將數(shù)組的每個(gè)元素四舍五入到小數(shù)點(diǎn)后兩位:
arr = np.round(arr, 2)Here’s the new array:
這是新的數(shù)組:
array([0.69, 0.94, 0.66, 0.73, 0.83])如何從NumPy數(shù)組返回特定??元素 (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數(shù)組中選擇(并返回)特定元素:使用方括號(hào)。
An example is below:
下面是一個(gè)示例:
arr[0]#Returns 0.69We 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.
我們還可以使用冒號(hào)運(yùn)算符引用NumPy數(shù)組的多個(gè)元素。 例如,索引[2:]從索引2開始選擇每個(gè)元素。 索引[:3]選擇直到索引3的每個(gè)元素,但不包括索引3。索引[2:4]返回從索引2到索引4的每個(gè)元素,但不包括索引4。始終排除較高的端點(diǎn)。
A few example of indexing using the colon operator are below.
下面是使用冒號(hào)運(yùn)算符建立索引的一些示例。
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數(shù)組中的元素分配 (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).
我們可以使用=運(yùn)算符將新值分配給NumPy數(shù)組的元素,就像常規(guī)的python列表一樣。 下面是幾個(gè)示例(請(qǐng)注意,這都是一個(gè)代碼塊,這意味著元素分配是逐步進(jìn)行的)。
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中的數(shù)組引用 (Array Referencing in NumPy)
NumPy makes use of a concept called ‘a(chǎn)rray referencing’ which is a very common source of confusion for people that are new to the library.
NumPy使用了一個(gè)稱為“數(shù)組引用”的概念,這對(duì)于圖書館新手來說是一個(gè)很常見的困惑源。
To understand array referencing, let’s first consider an example:
為了理解數(shù)組引用,我們首先考慮一個(gè)示例:
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也改變了價(jià)值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.
默認(rèn)情況下,當(dāng)您使用=賦值運(yùn)算符引用原始數(shù)組變量時(shí),NumPy不會(huì)創(chuàng)建數(shù)組的副本。 相反,它只是將新變量指向舊變量,這允許第二個(gè)變量對(duì)原始變量進(jìn)行修改-即使這不是您的意圖。
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.
這可能看起來很奇怪,但是確實(shí)有一個(gè)合理的解釋。 數(shù)組引用的目的是節(jié)省計(jì)算能力。 使用大型數(shù)據(jù)集時(shí),如果每次要使用陣列的一部分時(shí)都創(chuàng)建了一個(gè)新的陣列,則會(huì)很快用完RAM。
Fortunately, there is a workaround to array referencing. You can use the copy method to explicitly copy a NumPy array.
幸運(yùn)的是,有一種解決數(shù)組引用的方法。 您可以使用copy方法顯式復(fù)制NumPy數(shù)組。
An example of this is below.
下面是一個(gè)示例。
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.
如下所示,對(duì)復(fù)制的數(shù)組進(jìn)行修改不會(huì)更改原始數(shù)組。
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.
到目前為止,在本節(jié)中,我們僅探討了如何引用一維NumPy數(shù)組。 現(xiàn)在,我們將探討二維數(shù)組的索引。
索引二維NumPy數(shù)組 (Indexing Two-Dimensional NumPy Arrays)
To start, let’s create a two-dimensional NumPy array named mat:
首先,讓我們創(chuàng)建一個(gè)名為mat的二維NumPy數(shù)組:
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數(shù)組有兩種方法:
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:
我個(gè)人更喜歡使用mat[row][col]命名法進(jìn)行索引,因?yàn)樗子谥鸩斤@示。 例如:
#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:
您還可以使用以下符號(hào)從二維NumPy數(shù)組生成子矩陣:
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.
數(shù)組引用也適用于NumPy中的二維數(shù)組,因此,如果要避免在將原始數(shù)組的一部分保存為新變量名后避免無意間修改原始數(shù)組,請(qǐng)務(wù)必使用copy方法。
使用NumPy數(shù)組進(jìn)行條件選擇 (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數(shù)組支持稱為conditional selection的功能,該功能使您可以生成一個(gè)新的布爾值數(shù)組,該值指示數(shù)組中的每個(gè)元素是否滿足特定的if語句。
An example of this is below (I also re-created our original arr variable since its been awhile since we’ve seen it):
下面是一個(gè)示例(自從我們看到它以來已經(jīng)有一段時(shí)間了,我還重新創(chuàng)建了我們的原始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).
您也可以通過將條件傳遞到方括號(hào)中來生成滿足該條件的新值數(shù)組(就像我們對(duì)索引所做的一樣)。
An example of this is below:
下面是一個(gè)示例:
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.
有條件的選擇會(huì)比這復(fù)雜得多。 我們將在本節(jié)的相關(guān)實(shí)踐問題中探索更多示例。
繼續(xù) (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.
在本節(jié)中,我們將詳細(xì)探討NumPy數(shù)組的索引和賦值。 在下一部分中,我們將通過解決一系列實(shí)踐問題來進(jìn)一步鞏固您對(duì)這些概念的了解。
最后的想法和特別優(yōu)惠 (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軟件包之一,也是每個(gè)Python開發(fā)人員都必須知道的庫。
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 。 如果您有興趣學(xué)習(xí)更多Python核心技能,那么注冊的前50位freeCodeCamp讀者均可享受該課程50%的折扣- 單擊此處立即獲得折扣課程 !
翻譯自: https://www.freecodecamp.org/news/the-ultimate-guide-to-the-numpy-scientific-computing-library-for-python/
python包numpy
總結(jié)
以上是生活随笔為你收集整理的python包numpy_NumPy Python科学计算软件包的终极指南的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到自己剃光头发是什么意思
- 下一篇: 梦到大蟒蛇了有什么兆头