Slices (slicing) and indexes of numpy matrices (indexing)

Source: Internet
Author: User
Tags true true
Slice (slicing) action

The slice operations of multidimensional data in NumPy are the same as those in Python for list slices. The parameters are composed of three parts of Start,stop,step.

Import NumPy as np

arr = Np.arange (a)
print ' array is: ', arr

slice_one = arr[:4]
print ' slice begins at 0 And ends at 4 are: ', slice_one

slice_two = arr[7:10]
print ' slice begins at 7 and ends at: ', Slice_two

s Lice_three = Arr[0:12:4]
print ' slice begins at 0 and ends in with step 4 is: ', slice_three
The array is: [0  1 2 3 4 5 6 7 8  9 a  ]
slice begins at 0 and ends in 4 is : [0 1 2 3]
slice begins at 7 and ends in: [7 8 9]
slice begins at 0 and ends at: [4 0 4 ]

The above is an example of numpy manipulating one-dimensional data, and if it is a multidimensional array, just separate each dimension with a comma .

Note: The slices are open after the front closure, i.e. the slice results include start, but not the stop

# coding:utf-8
Import numpy as np

arr = Np.arange. Reshape ((3, 4))
print ' array is: '
print arr

# Fetch The first-dimensional index 1 to the element between index 2, that is, the second line
# takes the second-dimensional index 1 through the index 3 element, that is, the second and third columns
Slice_one = Arr[1:2, 1:3]
print ' first slice is  : '
print Slice_one

# take all # of the first dimension
# 2 of the second dimension's index 0 to the end, the first column and the third column
slice_two = arr[:,:: 2]
Print ' Second slice is: '
print Slice_two
The array is:
[[0  1  2  3] [4 5 6  7]
 [8  9]]
Slice is:< C25/>[[5 6]]
second slice is:
[[0  2]
 [4  6]
 [8 10]]

For multidimensional arrays with more than 3 dimensions, you can also pass ' ... ' To simplify the operation

# coding:utf-8
Import numpy as np

arr = Np.arange. Reshape ((2, 3, 4))

print arr[1, ...]               # equivalent to Arr[1,:,:]
print arr[..., 1]               # equivalent to arr[:,:, 1]
[[EUR]
 [A]
 [[A]]
[[1  5  9]
 [13 17 21]]
index (indexing) Operation

The most common operation for multidimensional arrays is to get a value from a specific location, as follows:

# coding:utf-8
Import numpy as np

arr = Np.array ([
    [1, 2, 3, 4],
    [2, 4, 6, 8],
    [3, 6, 9,],
    [4, 8]
]
print ' The value of the second column in the second row: ', arr[1, 1]
Value of second column in second row: 4

Python, by contrast, gets the same location for the list as the following:

# coding:utf-8
arr = [
    [1, 2, 3, 4],
    [2, 4, 6, 8], [3, 6, 9,]
    ,
    [4, 8,,]
]
print ' Second row second column value: ', arr[1][1]
try: print ' The value of the second
    column in the second row (try to get it in numpy): ', arr[1, 1]
except Exception as E:
    Print str (e)
Second row, second column value: 4
The value of the second column in row two (try to get it in NumPy): List indices must be integers, not tuple

In contrast, it may be that two-dimensional arrays are not very different for the same operation, just imagine that if it is a 10-D array, then the Python index list will need 10 pairs [] to perform this standard operation, and the numpy operation requires only 1 pairs. Get multiple elements

In fact, in the NumPy index operation ' x = arr[obj] ', obj is not just a comma-separated sequence of numbers, but it can be more complex.

1. Comma-delimited array sequence

The length of the array sequence should be consistent with the length of each array in the multidimensional array's dimension consistent sequence

Import NumPy as np

arr = Np.array ([
    [1, 2, 3, 4],
    [2, 4, 6, 8],
    [3, 6, 9,],
    [4, 8,]
]) 
  print arr[[0, 2], [3, 1]]
[4 6]

For the above example, first select lines 1th and 3rd, then select the 1th column of 4th, and the 3rd column of the 2nd line to form a new array.

2.boolean/mask Index

The so-called Boolean index is the use of a Boolean expression to determine the index, such as the following example

Array ([[1, 2, 3, 4],
       [2, 4, 6, 8], [3, 6, 9,
       ],
       [4, 8, 12, 16]]

To take the element that is greater than 5:

Import NumPy as np

arr = Np.array ([[1, 2, 3, 4],
                [2, 4, 6, 8], [3, 6, 9,
                ], [4, 8,]
                ])
MA SK = arr > 5

print ' Boolean mask is: '
print mask

print Arr[mask]
Boolean mask is: [False false false] [false false True] [false True True  ]  True]
 [False  True  true  ]]
[6  8  6  9  8 12 16]
similarities and differences of slices and indexes

Slices and indexes are all ways to get the elements in an array, but they are different:

A slice gets a view of the original multidimensional array. Modifying the contents of a slice also causes the value of the original array to be changed to a continuous or sequential value in a certain step, and the index gets the value at any position, and the degree of freedom is greater.
From: NumPy operation multidimensional Array

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.