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(讀作“麻木派”)是您開始學習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接受三個參數:

  1. The start of the interval

    間隔的開始
  2. The end of the interval

    間隔結束
  3. 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.

類似地,我們可以使用minargmin方法在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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390310.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390310.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390310.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

NGINX原理 之 SLAB分配機制(轉)

1 引言 眾所周知&#xff0c;操作系統使用伙伴系統管理內存&#xff0c;不僅會造成大量的內存碎片&#xff0c;同時處理效率也較低下。SLAB是一種內存管理機制&#xff0c;其擁有較高的處理效率&#xff0c;同時也有效的避免內存碎片的產生&#xff0c;其核心思想是預分配。其按…

apk之間數據共享的方式

1、四大組件之ContentProvider大法2、shareUserId3、apk均去遠端獲取配置文件&#xff08;或接口&#xff09;4、AIDL&#xff08;bindService&#xff09;5、SharePreference設置為MODE_WORLD_READABLE|MODE_WORLD_WRITEABLE模式&#xff0c;由于存在安全問題&#xff0c;已被…

藍橋杯java 基礎練習 十六進制轉十進制

問題描述從鍵盤輸入一個不超過8位的正的十六進制數字符串&#xff0c;將它轉換為正的十進制數后輸出。注&#xff1a;十六進制數中的10~15分別用大寫的英文字母A、B、C、D、E、F表示。樣例輸入FFFF樣例輸出65535import java.math.BigInteger; import java.util.Scanner;public …

dynamic web module消失不見

2019獨角獸企業重金招聘Python工程師標準>>> 方法1&#xff1a;在project Facets選項中勾選Dynamic Web Module即可 方法2&#xff1a; 我用eclipse對項目進行修改名稱&#xff0c;修改成功后。項目就沒有Deployment Descriptor&#xff08;如下圖紅色框中&#xff…

576. 出界的路徑數

576. 出界的路徑數 給你一個大小為 m x n 的網格和一個球。球的起始坐標為 [startRow, startColumn] 。你可以將球移到在四個方向上相鄰的單元格內&#xff08;可以穿過網格邊界到達網格之外&#xff09;。你 最多 可以移動 maxMove 次球。 給你五個整數 m、n、maxMove、star…

telnet命令發送郵件

下面的例子是用qq的smtp服務器。 set localecho 本地回顯啟用 telnet smtp.qq.com 25 220 smtp.qq.com Esmtp QQ Mail Server helo sis 250 smtp.qq.com//服務器返回250 smtp.qq.com STARTTLS 220 Ready to start TLS//服務器返回 220 準備開啟TLS通訊 auth login 334 VXNlcm5h…

myelcipse和maven搭建項目

偷懶一下&#xff0c;完了補充 轉載&#xff1a;https://www.cnblogs.com/jr1260/p/6438811.html https://www.cnblogs.com/yangmingyu/p/6908519.html https://www.cnblogs.com/henuyuxiang/p/6288476.html 轉載于:https://www.cnblogs.com/0914lx/p/8342343.html

551. 學生出勤記錄

551. 學生出勤記錄 I 給你一個字符串 s 表示一個學生的出勤記錄&#xff0c;其中的每個字符用來標記當天的出勤情況&#xff08;缺勤、遲到、到場&#xff09;。記錄中只含下面三種字符&#xff1a; ‘A’&#xff1a;Absent&#xff0c;缺勤 ‘L’&#xff1a;Late&#xff…

JavaScript實現職責鏈模式

什么是職責鏈模式 職責鏈模式的定義是&#xff1a;使多個對象都有機會處理請求&#xff0c;從而避免請求的發送者和接收者之間的耦合關系&#xff0c;將這些對象連成一條鏈&#xff0c;并沿著這條鏈傳遞該請求&#xff0c;直到有一個對象處理它為止。舉個例子&#xff1a;當你從…

Metrics介紹和Spring的集成

參考&#xff1a; http://colobu.com/2014/08/08/Metrics-and-Spring-Integration/ https://www.cnblogs.com/yangecnu/p/Using-Metrics-to-Profiling-WebService-Performance.html

配置 aws cli_AWS CLI教程–如何安裝,配置和使用AWS CLI了解您的資源環境

配置 aws cliHow to get exactly the account and environment information you need to manage your AWS account using just the AWS CLI如何僅使用AWS CLI準確獲取管理AWS賬戶所需的賬戶和環境信息 Installing the AWS CLI is actually quite simple. The best way to get …

grep遞歸查找頭文件_Grep命令教程–如何使用遞歸查找在Linux和Unix中搜索文件

grep遞歸查找頭文件grep stands for Globally Search For Regular Expression and Print out. It is a command line tool used in UNIX and Linux systems to search a specified pattern in a file or group of files. grep代表全局搜索正則表達式并打印出來 。 它是UNIX和Li…

C++ 前置聲明

&#xff08;一&#xff09;class的前置聲明 class的前置聲明有兩種。 pre.hclass PreA {}; main.hclass PreA; class Main {};//或者 class Main {class PreA* A; }; (二) struct前置聲明 struct的前置聲明只能用第一種。 &#xff08;三&#xff09; 有typedef的前置聲明 Pr…

2.18 特殊權限set_uid 2.19 特殊權限set_gid 2.20 特殊權限stick_bit 2.21 軟鏈接文件 2.22 硬連接文件...

2019獨角獸企業重金招聘Python工程師標準>>> 特殊權限set_uid set_uid:該權限針對二進制可執行文件&#xff0c;使文件在執行階段具有文件所有者的權限&#xff1b; 通俗一點講就是&#xff0c;普通用戶想要訪問一個沒有其他用戶可執行權限的目錄時&#xff0c;暫時…

345. 反轉字符串中的元音字母

345. 反轉字符串中的元音字母 給你一個字符串 s &#xff0c;僅反轉字符串中的所有元音字母&#xff0c;并返回結果字符串。 元音字母包括 ‘a’、‘e’、‘i’、‘o’、‘u’&#xff0c;且可能以大小寫兩種形式出現。 示例 1&#xff1a; 輸入&#xff1a;s “hello” 輸…

通過制作數字桌面游戲和Web應用程序學習JavaScript

Building 2D games can be a great way to learn JavaScript, especially when working through the basics of complex tabletop game logic.制作2D游戲可能是學習JavaScript的好方法&#xff0c;尤其是在研究復雜的桌面游戲邏輯基礎時。 In this series, I’m going to intr…

【HAVENT原創】Node Express API 通用配置

為什么80%的碼農都做不了架構師&#xff1f;>>> ( 基于 Express 4.x ) 啟動文件 /app.js&#xff1a; var express require(express); var bodyParser require(body-parser); var proxy require(http-proxy-middleware); var path require(path);var index re…

C#使用Json.NET解析Json

本文轉載自 http://xiaosheng.me/2016/10/01/article25/ 最近在 C# 項目中需要使用到 Json 格式的數據&#xff0c;我簡單上網搜索了一下&#xff0c;基本上有兩種操作 Json 數據的方法&#xff1a; 使用 Windows 系統自帶的類使用第三方的包本著“第三方包一定有比系統自帶類優…

現在JavaScript日期–如何在JavaScript中獲取當前日期

Many applications you build will have some sort of a date component, whether its the creation date of a resource, or the timestamp of an activity. 您構建的許多應用程序都將具有某種日期組件&#xff0c;無論是資源的創建日期還是活動的時間戳。 Dealing with date…

233. 數字 1 的個數

給定一個整數 n&#xff0c;計算所有小于等于 n 的非負整數中數字 1 出現的個數。 示例 1&#xff1a; 輸入&#xff1a;n 13 輸出&#xff1a;6 示例 2&#xff1a; 輸入&#xff1a;n 0 輸出&#xff1a;0 解題思路 正確性證明 例如&#xff1a;對于n3015&#xff0c…