Numpy slice and index

Array axis

a= np.arange(24).reshape((2, 3, 4))
print(a)
print(a.ndim) #Dimension of array, i.e. axis
print(a.shape) #Shape of array
//Output:
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
3
(2, 3, 4)

Get the elements of the array according to the index

  • Subscript is an integer
  • Subscript is list
  • Subscript is an array
b = np.logspace(1, 3, 12).reshape(3, 4)
print(b)
print(b.shape)
#Subscript is an integer
print(b[0])
print(b[1][2])
#Subscript is the form of list to get elements
print(b[[0, 1]]) 

//Output:
[[  10.           15.19911083   23.101297     35.11191734]
 [  53.36699231   81.11308308  123.28467394  187.38174229]
 [ 284.80358684  432.87612811  657.93322466 1000.        ]]
(3, 4)
[10.         15.19911083 23.101297   35.11191734]
123.28467394420659
[[ 10.          15.19911083  23.101297    35.11191734]
 [ 53.36699231  81.11308308 123.28467394 187.38174229]]

As with lists, for arrays, the values corresponding to each index can be modified by index (subscript).

Slice of array

Basic slice is an extension of basic slice concept to n dimension in Python. A Python slice object is constructed by slice function provided by start, stop and step parameters to built-in function. This slice object is passed to array to extract part of array.

The array obtained by slicing shares a memory space and a view with the original array. When one of the arrays is modified, the other will also be modified.

import numpy as np

a = np.arange(10)
print(a)# [0 1 2 3 4 5 6 7 8 9]
s = slice(2, 7, 2)
print(s)# slice(2, 7, 2)
print(a[s])# [2 4 6]

b = a[2:7:2]
print(b)# [2 4 6]

# Slice a single element
b = a[5]
print(b)# 5

# Slice the elements that start with the index
print(a[2:])# [2 3 4 5 6 7 8 9]

# Slice elements between indexes
print(a[2:5])# [2 3 4]

# Two-dimensional array
# First array
import numpy as np

a = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print('Our array is:')
print(a)
print ('\n')
# This returns an array of elements in the second column:
print ('The elements in the second column are:')
print(a[..., 1])
print('\n')
# Now we slice all the elements from the second line:
print ('The elements in the second line are:')
print(a[1, ...])
print('\n')
# Now we slice back all the elements from the second column:
print ('The second column and its remaining elements are:')
print(a[..., 1:])
//Output:
[0 1 2 3 4 5 6 7 8 9]
slice(2, 7, 2)
[2 4 6]
[2 4 6]
5
[2 3 4 5 6 7 8 9]
[2 3 4]
//Our array is:
[[1 2 3]
 [3 4 5]
 [4 5 6]]


//The elements in the second column are:
[2 4 5]


//The elements in the second line are:
[3 4 5]


//The second column and its remaining elements are:
[[2 3]
 [4 5]
 [5 6]]

The array obtained by slicing shares a memory space and a view with the original array. When one of the arrays is modified, the other will also be modified.

Tags: Python

Posted on Sat, 21 Mar 2020 08:49:29 -0700 by pitn