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 ArraysNumPy数组
  • NumPy Indexing and AssignmentNumPy索引和分配
  • NumPy Methods and OperationsNumPy方法和操作

继续 (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

python包numpy_NumPy Python科学计算软件包的终极指南相关推荐

  1. 全面对比 MATLAB、Julia、Python,谁在科学计算中更胜一筹?

    数百种编程语言,各有优劣,各自也都有自己最为适用的场景.那么就科学计算领域而言,主流的 MATLAB.Julia.Python 会有哪些最为独特的优势呢?又存在哪些让开发者无力的缺陷?在本文中,我们将 ...

  2. python扩展库用于科学计算的有哪些_数据科学必备的十大 Python 库

    ​Python 已成为当今使用最广泛的编程语言之一,尤其是在数据科学领域. Python 是一种高性能的语言,易于学习和调试,并且具有广泛的库支持.这些库都有自己独特的功能,一些专注于数据挖掘,一些专 ...

  3. python 对比matlab_全面对比 MATLAB、Julia、Python,谁在科学计算中更胜一筹?

    原标题:全面对比 MATLAB.Julia.Python,谁在科学计算中更胜一筹? 数百种编程语言,各有优劣,各自也都有自己最为适用的场景.那么就科学计算领域而言,主流的 MATLAB.Julia.P ...

  4. python 科学计算基础教程电子版-自学Python 编程基础、科学计算及数据分析

    自学Python 编程基础.科学计算及数据分析 epub pdf mobi txt 下载 自学Python 编程基础.科学计算及数据分析 epub pdf mobi txt 下载 ☆☆☆☆☆ 李金 著 ...

  5. python编程入门与案例详解-自学Python 编程基础、科学计算及数据分析

    自学Python 编程基础.科学计算及数据分析 epub pdf mobi txt 下载 自学Python 编程基础.科学计算及数据分析 epub pdf mobi txt 下载 ☆☆☆☆☆ 李金 著 ...

  6. python支持强大的科学计算功能_用 Python 写高效科学计算程序设计

    1.科学计算中的突出问题及需求 概括一般科学计算的特点,主要包括四方面: 数值计算种类多 对于某个问题的求解,可能需要不同种类的函数,如三角函数,积分函数,概率统计函数以及某些特殊函数. 需要大量数值 ...

  7. python 模块 导入机制 模块搜索 Python包 发布python模块或程序

    python 模块 python模块:以.py结尾的代码文件.        顶层文件: 程序执行入口        模块文件1        模块文件2        模块文件3 在python中一 ...

  8. 【干货】Python爬虫/文本处理/科学计算/机器学习/数据挖掘兵器谱

    2019独角兽企业重金招聘Python工程师标准>>> 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开发语言是C/C++,但平时的很多文本 ...

  9. python包 wget_Python数据科学“冷门”库

    原标题 | Lesser Known Python Libraries for Data Science 作者 | Parul Pandey 译者 | CONFIDANT(福建师范大学).Seabis ...

最新文章

  1. 计算机网络实验可变长子网掩码,计算机网络实验3-子网掩码与划分子网实验报告.docx...
  2. 如何使用区块链技术进行项目开发
  3. python数据降维_使用python实现多维数据降维操作
  4. 深度学习(二十)——Ultra Deep Network, 图像超分辨率算法
  5. C#中改变进度条(progressbar)的颜色
  6. 苹果电脑可以装windows系统吗_不只是桌面,这个 Windows 皮肤可以帮你全局美化 Windows 系统
  7. lambda 流 peek java_JDK8 流与λ表达式
  8. JavaScript跨域解决方法大全
  9. 一维稳态导热的数值计算c语言,传热传质上机实习题(参考资料C语言)
  10. MegaCli常见命令
  11. Yoga安装Ubuntu后,wifi和亮度调节问题
  12. JAVA基础--继承(inheritance)
  13. 多人操作sqlite3数据库冲突问题解决方法
  14. add_subplot()--matplotlib
  15. 佳能g2810打印机扫描怎么用_canon g2810驱动下载
  16. 学习3 二维游戏动画合成(侠客行)
  17. 进度计划中的时间相关术语
  18. ipadmini1从9.3.5降级8.4.1最有效的方法
  19. STM32HAL----USB升级固件(DFU)
  20. OpenOCD failed tor read memory at $addr 错误

热门文章

  1. C语言指针转换为intptr_t类型
  2. 网易严选Java开发三面面经:南京黑马java培训怎么样
  3. 普通二本的辛酸Android面试之路,算法太TM重要了
  4. 一个例子彻底搞懂C++的虚函数和纯虚函数
  5. python学习day04
  6. JavaScript 代码规范
  7. 每天一个LINUX命令(pwd)
  8. [AlwaysOn Availability Groups] 健康模型 Part 2 ——扩展
  9. Debian 系统安装 Nagios 服务器监控端
  10. Axios的Vue插件(添加全局请求/响应拦截器)