Thursday, November 28, 2019

NumPy - Slicing and Indexing

By now I expect that you are familiar with slicing standard Python lists. The same knowledge applies when slicing one-dimensional NumPy arrays. You will also learn how to flatten arrays. Flattening arrays simply means converting a multidimensional array into a one-dimensional array.

The ravel() function can manipulate the shape of an array as follows:

Input
b
Output
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]]])

Input
b.ravel ()

Output
array([ 0, 1, 2, 3, 4, 5, 6, 7])

The flatten() function performs the same task as ravel() . However, the difference is that in the flatten function, the array is allocated new memory.

It is possible to set the shape of a tuple without using the reshape() function. This is done as follows:

Input
b.shape = (3,4)

Input
b

Output
array
([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11])

Transposition is a common procedure in linear algebra where you convert the rows into columns and columns into rows. Using the example above, we will have the following output:

Input
b.transpose = ()

Output:
array
([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11])

It is possible to stack an array by the depth, vertical alignment, or horizontal alignment. For this purpose, you will use the following functions:

● hstack()
● dstack()
● vstack()

For a horizontal stack, the ndarray tuple is as shown below:

Input:
hstack((a, b))

For a vertical stack, the ndarray tuple is as shown below:

Input:
vstack((a, b))

For a depth stack, the ndarray tuple is as shown below:

Input:
dstack((a, b))
Share:

0 comments:

Post a Comment