博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python中的Numpy数组索引
阅读量:2528 次
发布时间:2019-05-11

本文共 6029 字,大约阅读时间需要 20 分钟。

索引和选择 (Indexing and Selection)

# importing moduleimport numpy as np# array declarationarr = np.arange(0,11)# printing array print(arr)

Output

输出量

[ 0  1  2  3  4  5  6  7  8  9 10]

Now, to get the index of an element in a Numpy array, it is very similar to how the index is retrieved from a list, for example (Note: In python, the index starts from 0).

现在,要获取Numpy数组中元素的索引,例如,它与从列表中检索索引的方式非常相似( 注意:在python中,索引从0开始)。

# importing moduleimport numpy as np# array declarationarr = np.arange(0,11)# printing array print("arr:", arr)# printing elements based on index# returns element from given indexprint("arr[8]:", arr[8])# returns the elements between start, endprint("arr[1:5]:", arr[1:5])# returns the elements between start, endprint("arr[0:5]:", arr[0:5])#returns the elements until endprint("arr[:6]:", arr[:6])# returns the elements from startprint("arr[2:]:", arr[2:])

Output

输出量

arr: [ 0  1  2  3  4  5  6  7  8  9 10]arr[8]: 8arr[1:5]: [1 2 3 4]arr[0:5]: [0 1 2 3 4]arr[:6]: [0 1 2 3 4 5]arr[2:]: [ 2  3  4  5  6  7  8  9 10]

索引二维数组 (Indexing a 2-D array)

Consider the following example,

考虑以下示例,

# importing moduleimport numpy as np# 2-D arrayarr_2d = np.array([[10,15,20],[25,30,35],[40,45,50]])# printing arrayprint(arr_2d)

Output

输出量

[[10 15 20] [25 30 35] [40 45 50]]

There are two ways to access the index in a 2-D array – Double bracket and single bracket notation. However, the most preferred way is using Single bracket notation. Below are the examples of using double and single bracket notation.

在二维数组中有两种访问索引的方法- 双括号和单括号表示法 。 但是,最优选的方法是使用单括号表示法。 以下是使用双括号和单括号表示法的示例。

1) Double bracket notation

1)双括号符号

# importing moduleimport numpy as np# 2-D arrayarr_2d = np.array([[10,15,20],[25,30,35],[40,45,50]])# returns 2nd row 1st columnprint(arr_2d[1][0])# returns 1st row 3rd columnprint(arr_2d[0][2])

Output

输出量

2520

2) Single bracket condition

2)单括号条件

# importing moduleimport numpy as np# 2-D arrayarr_2d = np.array([[10,15,20],[25,30,35],[40,45,50]])# using slice notation return required valuesprint(arr_2d[:2,1:]) # returns 1st row 3rd columnprint(arr_2d[0,2])

Output

输出量

[[15 20] [30 35]]20

有条件的选择 (Conditional selection)

Suppose we have a NumPy array,

假设我们有一个NumPy数组,

import numpy as nparr = np.arange(1,11)print(arr)# output: [ 1  2  3  4  5  6  7  8  9 10]

Apply > operator on above created array

在上面创建的数组上应用>运算符

bool_arr = arr>4

Comparison Operator will be applied to each element in the array and the number of elements in returned bool Numpy Array will be the same as the original Numpy Array. But for every element that satisfies the condition, there will be True in an array and False for Others in the returned array. The contents of the array will be,

比较运算符将应用于数组中的每个元素,并且返回的布尔Numpy Array中的元素数量将与原始Numpy Array相同。 但是对于每个满足条件的元素,在数组中将为True,在返回的数组中为Other。 数组的内容将是

import numpy as nparr = np.arange(1,11)bool_arr = arr>4print(bool_arr)print(arr)

Output

输出量

[False False False False  True  True  True  True  True  True][ 1  2  3  4  5  6  7  8  9 10]

Now, to get the conditional results, pass the bool_arr to an arr object and only those elements are returned whose value is true,

现在,要获得条件结果,请将bool_arr传递给arr对象,然后仅返回值为true的那些元素,

print(arr[bool_arr])# Output: [ 5  6  7  8  9 10]

Implementing the above in a single step,

一步实现以上步骤,

import numpy as nparr = np.arange(1,11)print("arr...")print(arr)new_arr = arr[arr>6]print("new_arr...")print(new_arr)

Output

输出量

arr...[ 1  2  3  4  5  6  7  8  9 10]new_arr...[ 7  8  9 10]

广播功能 (Broadcasting functions)

Broadcasting is the method that NumPy uses to allow arithmetic between arrays with different shapes and sizes. Broadcasting solves the problem of arithmetic between arrays of differing shapes by in effect replicating the smaller array along with the mismatched dimension.

广播是NumPy用于允许在具有不同形状和大小的数组之间进行算术运算的方法 。 广播通过实际上复制较小的阵列以及不匹配的尺寸来解决不同形状的阵列之间的算术问题。

NumPy does not duplicate the smaller array; instead, it makes a memory and computationally efficient use of existing structures in memory that in effect achieve the same result.

NumPy不复制较小的数组。 取而代之的是,它对内存中的现有结构进行了存储并在计算上有效地使用了实际上达到相同结果的结构。

Example of broadcasting

广播示例

import numpy as nparr = np.arange(1,11)# printing array before broadcastingprint("arr before broadcasting...")print(arr)arr[0:5] = 123# printing array before broadcastingprint("arr before broadcasting...")print(arr)

Output

输出量

arr before broadcasting...[ 1  2  3  4  5  6  7  8  9 10]arr before broadcasting...[123 123 123 123 123   6   7   8   9  10]

An important behavior of broadcasting is explained in the below example,

下例说明了广播的重要行为,

import numpy as nparr = np.arange(0,11)# slice the arraysliced_arr = arr[0:5] print(sliced_arr)# broadcast the indicated number to 99sliced_arr[:] = 99 print(sliced_arr)# broadcasting also changes the parent arrayprint(arr)

Output

输出量

[0 1 2 3 4][99 99 99 99 99][99 99 99 99 99  5  6  7  8  9 10]

The reason NumPy does the above is to avoid the memory issue while handling large arrays. In order to retain the original values, there is an option to copy the array explained in below example,

NumPy进行上述操作的原因是为了避免在处理大型数组时出现内存问题。 为了保留原始值,有一个选项可以复制下面示例中说明的数组,

import numpy as nparr = np.arange(0,11)print(arr)arr_copy = arr.copy()print(arr_copy)arr_copy[:] = 1print(arr_copy)# the parent array is not modifiedprint(arr)

Output

输出量

[ 0  1  2  3  4  5  6  7  8  9 10][ 0  1  2  3  4  5  6  7  8  9 10][1 1 1 1 1 1 1 1 1 1 1][ 0  1  2  3  4  5  6  7  8  9 10]

General broadcasting rules

一般广播规则

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions and works its way forward. Two dimensions are compatible when,

在两个数组上进行操作时,NumPy逐元素比较其形状。 它从尾随尺寸开始,一直向前发展。 当,

  1. they are equal, or

    它们相等,或者

  2. one of them is 1

    其中之一是1

If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays.

如果不满足这些条件,则将引发ValueError :操作数不能一起广播的异常,这表明数组的形状不兼容。 所得数组的大小是沿输入数组每个维度的最大大小。

翻译自:

转载地址:http://fbvzd.baihongyu.com/

你可能感兴趣的文章
如何用纯 CSS 创作一个 3D 文字跑马灯特效
查看>>
assert.notDeepEqual()
查看>>
android获取textview的行数
查看>>
winsocket客户端编程以及jmeter外部调用
查看>>
PHP基础知识------页面静态化
查看>>
zoj 3747 dp递推
查看>>
POJ 3740
查看>>
41025 ISD Assignment 2 Autumn 2019
查看>>
JavaScript跨域调用基于JSON的RESTful API
查看>>
js 右击事件
查看>>
POJ1426:Find The Multiple(算是bfs水题吧,投机取巧过的)
查看>>
今天突然出现了Property IsLocked is not available for Login '[sa]',我太阳,下面有绝招对付它!...
查看>>
django-admin源码解析
查看>>
pc端字体大小自适应几种方法
查看>>
Linux--Linux下安装JDk
查看>>
Github windows客户端简单上手教程
查看>>
前端面试题:高效地随机选取数组中的元素
查看>>
[.NET] 使用 .NET Framework 開發 ActiveX Control
查看>>
Remote IIS Debugging : Debug your ASP.NET Application which is hosted on "Remote IIS Server"
查看>>
iframe 模拟ajax文件上传and formdata ajax 文件上传
查看>>