Mastering NumPy - Part 2 (Array Manipulation)
Mastering NumPy - Part 2 (Array Manipulation)
Manipulation)
Nandeda Narayan
·
Follow
9 min read
May 24
16
This is the 3rd blog post in our comprehensive series (Access all posts of this
series here) on NumPy!
Once you have created arrays, the next step is to manipulate and transform them
to suit your specific needs. NumPy offers an extensive set of functions for array
manipulation, including reshaping, slicing, concatenating, and more. In this blog
post, we will explore ten practical examples of array manipulation using NumPy,
showcasing the power and flexibility of these operations.
import numpy as np
In this example, we create a NumPy array arr with elements [1, 2, 3, 4, 5]. We then
access a specific element, next we use slicing to access a range of elements.
2nd part of the program shows slicing and accesing of array elements of a 2D
array.
2. Reshaping an array using numpy.reshape()
In NumPy, the reshape() function allows you to change the shape of an array
without modifying its data. It returns a new array with the specified shape. The
elements in the original array are used in the same order to fill the new array.
Here, array is the original array that you want to reshape, new_shape is a tuple
specifying the new shape, and order is an optional parameter that determines the
order in which the elements are read from the original array. The default value is
'C', which means row-major order.
import numpy as np
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
In this example, the original array has 12 elements, and we reshape it into a 3x4
matrix using reshape(). The resulting reshaped array has the elements filled row by
row from the original array.
Note that the total number of elements in the original array must match the total
number of elements in the new shape. Otherwise, a ValueError will be raised.
import numpy as np
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# [1 2 3 4 5 6]
As you can see, the flatten() function has transformed the 2D array arr into a 1D
array flattened_arr. The elements of flattened_arr are in the same order as they
appear in arr, but in a flattened sequence.
It’s important to note that flatten() always returns a copy of the original array. If
you want to flatten the array in-place (modify the original array itself), you can use
the ravel() function instead:
In NumPy, you can use the numpy.transpose() function to transpose an array, which
swaps the dimensions of the array. The numpy.transpose() function takes the array
as the first argument and an optional axes parameter that specifies the new order
of dimensions.
import numpy as np
# Create a 2D array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
# Output
# Original Array:
# [[1 2 3]
# [4 5 6]]
# Transposed Array:
# [[1 4]
# [2 5]
# [3 6]]
In this example, the original array has dimensions (2, 3). After transposing, the
dimensions become (3, 2), swapping the rows and columns.
5. Concatenating two arrays horizontally using numpy.hstack()
horizontally, which means stacking them side by side. The numpy.hstack() function
takes a sequence of arrays as arguments and returns a single array formed by
stacking the arrays horizontally.
import numpy as np
# Concatenated Array:
# [1 2 3 4 5 6]
In this example, the arrays arr1 and arr2 are both 1-dimensional. By
using numpy.hstack(), they are concatenated horizontally, resulting in a single 1-
dimensional array [1, 2, 3, 4, 5, 6].
In NumPy, you can use the numpy.vstack() function to concatenate two arrays
vertically, which means stacking them on top of each other.
The numpy.vstack() function takes a sequence of arrays as arguments and returns a
single array formed by stacking the arrays vertically.
Here’s an example of how to use numpy.vstack() to concatenate two arrays
vertically:
import numpy as np
#Concatenated Array:
#[[1 2 3]
# [4 5 6]]
In this example, the arrays arr1 and arr2 are both 1-dimensional. By
using numpy.vstack(), they are concatenated vertically, resulting in a 2-dimensional
array [[1, 2, 3], [4, 5, 6]]. The first array arr1 becomes the first row, and the
second array arr2 becomes the second row of the concatenated array.
To split an array into multiple subarrays using numpy.split(), you need to specify
the array you want to split and the indices where you want the split to occur.
The numpy.split() function returns a list of subarrays.
import numpy as np
In the first example, we split the array arr1 into 3 equally-sized subarrays. In the
second example, we split the array arr2 at indices 2 and 4. In the third example, we
split the 2D array arr3 along axis 1, resulting in three subarrays.
To repeat elements within an array using numpy.repeat(), you can specify the array
and the number of repetitions for each element. The numpy.repeat() function
returns a new array with repeated elements.
import numpy as np
In the first example, we repeat each element of arr1 twice. In the second example,
we repeat each element of arr2 a different number of times specified by
the repeats2 array. In the third example, we repeat the elements of the 2D
array arr3 twice along axis 1, resulting in a new array with repeated elements.
9. Removing duplicate elements from an array using numpy.unique()
In NumPy, you can use the numpy.unique() function to remove duplicate elements
from an array. The numpy.unique() function returns a sorted, unique copy of an
array.
import numpy as np
print(unique_arr)
# output: [1 2 3 4 5]
Note that numpy.unique() returns the sorted unique elements by default. If you
want to preserve the original order of the elements, you can
pass return_index=True and use the returned indices to obtain the unique elements
in the original order:
import numpy as np
In this case, unique_elements contains the unique elements, and indices contains
the indices of the first occurrences of those unique elements in the original array.
By sorting the indices and indexing the original array arr, we
obtain unique_arr with the original order of the unique elements.
In NumPy, you can use the numpy.random.shuffle() function to shuffle the elements
within an array. The numpy.random.shuffle() function randomly rearranges the
elements of the input array along the first axis.
import numpy as np
# Example array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# [3 2 4 1 5]
In the above example, the array arr contains elements [1, 2, 3, 4, 5]. By
calling np.random.shuffle(arr), the elements of arr are randomly rearranged along
the first axis. As a result, arr is shuffled, and the output may vary each time you
run the code.
Note that numpy.random.shuffle() shuffles the array in-place, meaning it modifies
the original array directly. If you want to create a shuffled copy of the array without
modifying the original array, you can use the numpy.random.permutation() function
instead:
import numpy as np
# Example array
arr = np.array([1, 2, 3, 4, 5])
print(shuffled_arr)
# [4 2 1 5 3]
Conclusion