NumPy – Arithmetic, Indexing, Shape Manipulation

One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python sequences.

Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by commas:

print("Program Name: numpy_indexing_in_arrays.py \n")
# Indexing in NumPy arrays
import numpy as np
def arr(i, j):
    return(i + j**2)
#Call function arr in fromfunc()procedure.
print("Create an array named 'myarray' of size 5x4. \n")
myarray = np.fromfunction(arr, (5, 4), dtype = int)
print("The array created by formfuncton arr is: ")
print(myarray)
print()
# Let us print by Indexing
# print the last row
print("The last row of array 'myarray' is:\n ",myarray[-1])
#
print()
# print the first row
print("The first row of array 'myarray' is: \n ", myarray[0, ])
print()
# Print the first column
print("The first column of array 'myarray' is:\n ",myarray[ : , 0])
print()
# Print the last column
print("The last column of array 'myarray' is:\n ",myarray[ : , 3])
print()
# print rows[1, 2]
print("The rows 1 and 2 of array 'myarray are: \n ", myarray[1:3, : ])
#
print()
# print columns[1, 2]
print("The columns 1 and 2 of array 'myarray' are : \n ", myarray[:, 1:3 ])
print()
# using negative index
# Print the last column using negative index
print("The last column of array 'myarray' using negative index is:\n ",myarray[ : , -1])
print()
# print the element 3rd row, 2nd column
print("Elements last row and  column (0,1) of array 'myarray' are: ",myarray[-1 , 0:2])

The following is the program’s output.

Program Name: numpy_indexing_in_arrays.py

Create an array named ‘myarray’ of size 5×4.

The array created by formfuncton arr is:
[[ 0 1 4 9]
[ 1 2 5 10]
[ 2 3 6 11]
[ 3 4 7 12]
[ 4 5 8 13]]

The last row of array ‘myarray’ is:
[ 4 5 8 13]

The first row of array ‘myarray’ is:
[0 1 4 9]

The first column of array ‘myarray’ is:
[0 1 2 3 4]

The last column of array ‘myarray’ is:
[ 9 10 11 12 13]

The rows 1 and 2 of array ‘myarray are:
[[ 1 2 5 10]
[ 2 3 6 11]]

The columns 1 and 2 of array ‘myarray’ are :
[[1 4]
[2 5]
[3 6]
[4 7]
[5 8]]

The last column of array ‘myarray’ using negative index is:
[ 9 10 11 12 13]

Elements last row and column (0,1) of array ‘myarray’ are: [4 5]

The NumPy shape function is used to determine the dimensions of an array. An array’s shape is given by the number of elements in each axis.

For example, a 2D array with “m” rows, and “n” columns has shape (m, n).

The shape function returns a tuple that indicates the number of elements along each axis of the array.

The shape of an array can be changed with various commands. Note that the following three commands all return a modified array, but do not change the original array:

print("Program Name: shape.py \n")
import numpy as np
# Create a 2-D array named 'a'.
a = np.array([[2, 3, 4, 5, 6] , [5, 6, 7, 8, 9]])
# Find the shape of the array 'a'.
x = a.shape # Shape of the array
print("The shape of the array 'a' is: \n", x)

The following is the program’s output.

Program Name: shape.py

The shape of the array ‘a’ is:
(2, 5)

For more details, click the following link:

https://numpy.org/doc/stable/reference/routines.array-manipulation.html

The NumPy reshape() function changes the shape of an array without altering its data. Note that the total of elements in the new shape remain the same as in the original array.

Features:

  • Change Shape: Modify the dimensions of an array.
  • Data Preservation: The data within the array remains unchanged.
  • Element Count Consistency: The total number of elements must be the same in both the original and new shapes.

The Syntax of the reshape() function is:

numpy.reshape(a/shapeorder=’C’*copy=None)

ParameterDescriptionNotesReturns
aArray to be shaped reshaped_array : ndarray  
shapeNew shape specified in int or tuple of ints# of elements in the new array must be same as in the original array 
orderOptional  
copyOptional  

In the following sections, the name of the array is assumed to be ‘a’.

The program below uses the reshape() function to change the shape of an array without altering the data.

Program Example: reshape() Function

# Program Name: reshape.py
import numpy as np
# Create an 2-D array named 'a'.
a = np.array([[2, 3, 4, 5, 6, 11] , [5, 6, 7, 8, 9, 10]])
print("2-D array 'a' is: \n",a)
print()
x = a.shape # Shape of the array
print("The shape of the array 'a' is: \n", x)
print()
print("Now use the reshape() function to shange the shape of array to 4x3. \n")
# Change the shape to (4, 3) and name the reshaped array 'y'.
y = a.reshape(4, 3)
print("The reshaped array is: \n", y)

The following is the program’s output.

2-D array ‘a’ is:
[[ 2 3 4 5 6 11]
[ 5 6 7 8 9 10]]

The shape of the array ‘a’ is:
(2, 6)

Now use the reshape() function to shange the shape of array to 4×3.

The reshaped array 4×3 is:
[[ 2 3 4]
[ 5 6 11]
[ 5 6 7]
[ 8 9 10]]

numpy.ravel() Function

NumPy’s ravel function is used to flatten a multi-dimensional array into a one-dimensional array. The function is useful in memory usage efficiency.

Syntax:

numpy.ravel(aorder=’C’)

Table

ParameterDescriptionNotesReturns
aArray to be flattenedThe elements in a are read in the order specified by order, and packed as a 1-D array Contiguous 1-D array of the same subtype as a
orderOptionalThis specifies the order in which the array elements are read.  

The program below flattens a two-dimensional array.

print("Program Name:ravel.py \n")
import numpy as np
print("Create a 2-D array named 'a'.")
a = np.array([[2, 3, 4, 9] , [5, 6, 7, 10]])
print("array 'a' is: \n", a)
# Flatten the array using ravel() command and call it array 'b'.
b = a.ravel()
print("The flattened array 'b' is: \n", b)

The following is ravel.py program’s output.

Program Name:ravel.py

Create a 2-D array named ‘a’.
array ‘a’ is:
[[ 2 3 4 9]
[ 5 6 7 10]]
The flattened array ‘b’ is:
[ 2 3 4 9 5 6 7 10]

Transpose Function

The NumPy transpose() function is used to change the orientation of an array by reversing its axes, effectively switching rows with columns in a 2D array.

This function is used in data manipulation and linear algebra.

For more details, click on the link.

https://numpy.org/doc/stable/reference/generated/numpy.transpose.html

Syntax: numpy.transpose(aaxes=None)

ParameterDescriptionNotesReturns
aInput array to be transposed.The elements in a are read in the order specified by order, and packed as a 1-D arrayReturns an array with axes transposed.  
AxesOptional tuple or a list of ints  Specifies the order of the axes. If not provided, the default behavior reverses the dimensions. 

The program example switches the rows and columns of 2×4 2D array.

Program Example Transpose Function

#array transpose command
import numpy as np
a = np.array([[2, 3, 4, 9] , [5, 6, 7, 10]])
print( "The original array is: \n", a)
x = a.shape
print("The shape of the original array is : \n", x)
print()
# Transpose the array using a.T command
b = a.T.shape
print("The shape of the transposed array is: \n", b)

The following is the program’s output.

The original array is:

 [[ 2  3  4  9]

 [ 5  6  7 10]]

The shape of the original array is :

 (2, 4)

The shape of the transposed array is:

 (4, 2)

resize() Method

The NumPy resize() function creates a new array with a specified shape and size.

The reshape function returns its argument with a modified shape, whereas the ndarray.resize method modifies the array itself.  See the program below.

Syntax:

Numpy.resize(a, newshape))

ParametersDescriptionReturns
a:  is the array to be resizedThe new array is formed from the data in the old array.Reshaped array: ndarray
newshape: shape of the resized array int or tuple (int)  

For more exploration, click the link below.

https://numpy.org/doc/stable/reference/generated/numpy.resize.html

The following program example of resize() function. The function changes a (2,6) 2-D array to

(6,2) array.  Note that the original array itself has been modified, as opposed to reshape() function that does not change the original array.

Program Example resize() Function

#array resize() function
import numpy as np
a = np.array([[2, 3, 4, 9, 12, 14] , [5, 6, 7, 10, 25, 18]])
print( "The original array is: \n", a)
print()
x = a.shape
print("The shape of the original array is : \n", x)
print()
# Resize the array 'a' using the resize() method to size (6, 2)
a.resize((6, 2))
print("The resized array  is: \n", a)
print()
# Note that the resize() function modified to original array 'a' itself.
print("The resized array shape is \n ",a.shape)

The following is the program’s output.

The original array is:

 [[ 2  3  4  9 12 14]

 [ 5  6  7 10 25 18]]

The shape of the original array is :

 (2, 6)

The resized array  is:

 [[ 2  3]

 [ 4  9]

 [12 14]

 [ 5  6]

 [ 7 10]

 [25 18]]

The resized array shape is

  (6, 2)

Stacking Together Different Arrays

NumPy allows you to stack several arrays together vertically or horizontally.

Vertical Stack numpy.vstack()

Numpy.vstack() function stacks arrays in sequence vertically (row wise).

The numpy.vstack() function is used to stack arrays vertically, meaning it combines them on top of each other. It requires that the arrays have the same number of columns to work properly.

Syntax:

numpy.vstack(tup*dtype=Nonecasting=’same_kind’)

ParameterDescriptionNotesReturns
tup : sequence of ndarraysA tuple of arrays to be stacked vertically.The arrays must have the same shape along all but the first axis. 1 
dtype : str or dtypeOptional  
castingOptional  

For more details, click the link below:

https://numpy.org/doc/stable/reference/generated/numpy.vstack.html

The following program is an example of stacking two 2D arrays vertically.

Program Example Vertical Stack

#array vertical stack
import numpy as np
# Create two arrays to be stacked
arr1 = np.array([[2, 3,4], [5, 6, 7]])
print( "The arr1 is: \n", arr1)
print()
# Create second array to be stacked.
arr2 = np.array([[8, 9, 10], [12, 13, 14]])
print( "The arr2 is: \n", arr2)
print()
vstack_array = np.vstack((arr1, arr2))
print(" Vetical stacked array is: \n", vstack_array)
#print(stacked_array)

The following is the program’s output.

The arr1 is:

 [[2 3 4]

 [5 6 7]]

The arr2 is:

 [[ 8  9 10]

 [12 13 14]]

 Vetical stacked array is:

 [[ 2  3  4]

 [ 5  6  7]

 [ 8  9 10]

 [12 13 14]]

Horizontal Stack:  numpy.hstack() Function

The numpy.hstack() function is used to horizontally stack arrays in NumPy, meaning it combines them side by side along the second axis (columns). This function requires that the arrays have the same number of rows to be concatenated successfully.

Syntax:

numpy.hstack(tup*dtype=Nonecasting=’same_kind’)

ParameterDescriptionReturns
tup : sequence of ndarraystup: A tuple or list of arrays to be stacked. All arrays must have the same shape except along the axis being concatenated.The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length. 
dtype : str or dtypeOptional  
castingOptional  

The following program is an example of stacking two 2D arrays horizontally.

Program Example Horizontal Stack

#array horizontal stack
import numpy as np
# Create two arrays to be stacked
arr1 = np.array([[2, 3,4], [5, 6, 7]])
print( "The arr1 is: \n", arr1)
print()
# Create second array to be stacked.
arr2 = np.array([[8, 9, 10], [12, 13, 14]])
print( "The arr2 is: \n", arr2)
print()
hstack_array = np.hstack((arr1, arr2))
print(" Horizontal stacked array is: \n", hstack_array)

The following is the program’s output.

The arr1 is:

 [[2 3 4]

 [5 6 7]]

The arr2 is:

 [[ 8  9 10]

 [12 13 14]]

 Horizontal stacked array is:

 [[ 2  3  4  8  9 10]

 [ 5  6  7 12 13 14]]

Verified by MonsterInsights