NumPy operation of Array objects-indexing mechanism, slicing, and iteration methods

Source: Internet
Author: User

I wrote about array creation and data operations, and now let's look at how array objects work. Use the methods of indexing and slicing to select elements, and how to iterate over arrays.

I. Indexing mechanism 1. One-dimensional arrays
In [1]: a = Np.arange (10,16) in [2]: aout[2]: Array ([Ten, One,,, +]) #使用正数作为索引In [3]: a[ 3]out[3]:#还可以使用负数作为索引In [4]: a[-4]out[4]: 12# square brackets Pass in most index values, multiple elements can be selected at the same time
In [6]: a[[0,3,4]]
OUT[6]: Array ([10, 13, 14])

2. Two-dimensional array

A two-dimensional array, also known as a matrix, is made up of rows and columns. The axes is 2, the row is represented by 0 axes, and the column is represented by 1. [row index, column index]

In []: aout[]:array ([[Ten, one,       ], [+], [[+],       [+]])
#取出第三行第二列的元素In []: a[2,1]out[15]: 17
#可以使用方括号取出多个元素In [+]: a[[[2,1],[1,2]]]out[17]: Array ([17, 15])

Second, slicing operation: extracting some array elements to generate a new array 1. One-dimensional array slicing operations
in [+]: a = Np.arange (10,20) in [+]: A[2:7]out[+]: Array ([12, 13, 14, 15, 16]) in []: A[5:8]out[: Array ([15, 16, 17])#Set Step sizein [+]: a[2:8:2]out[: Array ([12, 14, 16])#omitting the first number is considered to be starting from 0 (the first element)In [to]: A[:8:2]out[+]: Array ([10, 12, 14, 16])#omitting the second number is considered to be the maximum index valuein [+]: a[5::2]out[+]: Array ([15, 17, 19])#omitting the third number, the step is considered to be 1in [[]: A[5:8:] out[: Array ([15, 16, 17])#omitting the first two numbers is considered to be the selection of all elements of step xIn [A[::2]:]out[: Array ([10, 12, 14, 16, 18])
2. Two-d array slicing operations

The slicing operation of a two-dimensional array is similar to a one-dimensional array, except that a single axis is read, and there are two values (separated by commas) in the square brackets, so that the left and right sides of the comma can be treated as an array, for example: A[0:2,0:2]

In [1]: A = Np.arange (10,19). Reshape (3,3) in [2]: aout[2]:array ([[10, 11, 12],       [13, 14, 15],       [16, 17, 18]]) #第一个索引使用了冒号, then all rows are taken and the second index is 0, which means the first column is selected. That is, all elements of the first column in [3]: a[:,0]out[3]: Array ([10, 13, 16]) in [4]: a[0,:]out[4]: Array ([10, 11, 12])
#行选取了0:2, that is, the first second row (the right side of the colon is the end value, not within the selection), and the column is the same in the [5]: A[0:2,0:2]out[5]:array ([[10, 11], [13, 14]])
#如果要选取不连续的元素, you can put these indexes in an array. The following is the selection of the first and third rows, the elements in the first and second columns in [6]: A[[0,2],0:2]out[6]:array ([[10, 11], [16, 17]])

3. Note: Python's slice of the list gets a copy of the array, and the numpy array slice gets a view that points to the same buffer. As the original data changes, the resulting array of slices will change as well.

Iii. iteration of an array

When we use a function to manipulate rows, columns, or individual elements, we need to iterate over the array.

1. One-dimensional array, using the for: In the loop can

In [7]: a = Np.arange (0,11) in [8]: aout[8]: Array ([0,  1,  2,  3,  4,  5  , 6,  7,  8,  9, ten]) in [ for in A:   ...:     Print  I012345678910

2. Two-dimensional array

You can also use a for loop for nesting. But in fact, you'll find that it always scans the two-dimensional array by the first axis.

 for inch A: ...    :     print  row ...    : [ten] [] [16 1718]

If you want to iterate through each element of the array. Can iterate through A.flat

 for inch A.flat: ...    :     print  i101112131415161718

The For loop is less elegant, NumPy provides a more elegant way to traverse: Apply_along_axis (Func,axis,arr), which can use an aggregate function to process each column or row and return a numeric value as the result.

This function receives three parameters, the first is the aggregate function, the second is the corresponding axis (axis=0 by column , Axis=1 by Row), and the third is the array to be processed

In []: aout[]:array ([[Ten, one,       ], [+], [[+],       [+]])  #Axis 1, operation by row, output the maximum value per line in []: Np.apply_along_axis (np.max,axis=1,arr=A) out[ []: Array ([[K], +])# outputs the average of each line in [+]: Np.apply_along_axis (Np.mean,axis=1 , arr=A) out[]: Array ([one.,  17.])

Where the first argument can pass a function of its own writing

def foo (x):    ...:     return x/2 in[]: Np.apply_along_axis (foo,axis=1,arr=A) out[ ]:array ([[5, 5, 6],       [6, 7, 7],       [8, 8, 9]])

Iv. using conditional expressions and Boolean operators to selectively extract elements

 in [c]: B = Np.random.random ((3,3 21]: bout[ 21]:array ([[ 0.11802695, 0.66445966, 0.06007488", [ 0.31908974, 0.35200425, 0.64225707 0.60802331, 0.93322485, 0.28177795]])  #   Get a Boolean array from the conditional expression  in []: B < 0.5out[ 22]:array ([[True, False, True], [true, True, false], [False, False, true]], Dtype  =bool)  #   Put the conditional expression in square brackets, you can extract an array that satisfies the expression, forming a new array.   in [all]: B[b<0.5]out[: Array ([0.11802695, 0.06007488, 0.31908974, 0.35200425, 0.28177795]) 

V. Summary

Learn about the indexing mechanism of arrays, slicing operations on an array, and traversing.

NumPy operation of Array objects-indexing mechanism, slicing, and iteration methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.