NumPy- the underlying index and sliced

The underlying index and sliced

First you create a new volume a ndarray array:

arr = np.arange(10)

And a list of similar python, you can be the value by indexing and slicing

print(arr[6]) #索引从0开始
print(arr[5:8]) #顾头不顾尾

6
[5 6 7]

Just like a list, array slices also care regardless of the value of the tail, and the index is zero-based.

Important example

arr = np.arange(10)
piece_of_arr = arr[4:6]
piece_of_arr[:] = 24
print(arr)

[ 0 1 2 3 24 24 6 7 8 9]

Yes, different from Python's built-in list, a slice of the array is an array of original view, it means that the data is not copied copy for any career changes will be reflected in the original array.

Compared to other array of programming languages ​​they are more eager to replicate data, due NumPy is designed to be suitable for handling very large array, so it will not so easily allow developers to replicate, you can think about what would happen if the continuous replication of data NumPy how much can cause memory problems.

But if you still want a slice of the array copy, not a view, then it must be explicitly copied the array,

For example: ARR [. 5:. 8] .copy ()

Slice indexed array

import numpy as np
arr1 = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr1)
print('-----------')
print(arr1[:2])
print('-----------')
print(arr1[:2, 1:])
print('-----------')
print(arr1[1,:2])
print('-----------')
print(arr1[:,:1])
print('-----------')
arr1[:2, 1:] = 0
print(arr1)
print('-----------')

result

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

Guess you like

Origin www.cnblogs.com/chanyuli/p/11716979.html