Mastering NumPy: Useful Methods for Efficient Array Manipulation

ShehzifiedShehzified
5 min read

๐ŸŽฏ Introduction

Discover how to make the most of NumPy with these useful methods that simplify working with arrays. These techniques will help you code faster and with less hassle, making your experience with NumPy more enjoyable and efficient.

โš™๏ธ Methods

Here are the 17 useful methods that will help you work with arrays more efficiently, all in one line:

np.sort()

This method sorts the array in ascending order, the same as list sort. You can also provide an axis to sort column-wise or rows-wise.

a = np.random.randint(1,100,15)
a = np.sort(a)[::-1] # slicing for reverse

np.append()

This method appends the new item to an array, you can also append another array to the end or axis-wise also.

a = np.random.randint(1,100,15)
b = np.random.randint(1,100,24).reshape(6,4)
np.append(a,200) # append 200 at the end of 1D array
np.append(b,np.ones((b.shape[0],1)),axis = 1) # 1 to each row of array b having shape(6,4)

np.concatenate()

This method will concatenate multiple arrays at once along the provided axis.

c = np.arange(6).reshape(2,3)
d = np.arange(6,12).reshape(2,3)
np.concatenate((c,d)) # by default it will do col-wise concatenation
np.concatenate((c,d),axis=1) # axis = 1 for row-wise concatenation

np.unique()

This method will return a new array of unique elements from the array given as parameter in np.unique() method.

e = np.array([1,1,2,2,3,3,4,4,5,5,6,6])
np.unique(e) # output: array([1, 2, 3, 4, 5, 6])

np.expand_dims()

This method will expand dimensions of an array.
e.g: 1D โ€”โ†’ 2D and 2D โ€”โ€”โ†’ 3D and, So on.

a = np.random.randint(1,100,15)
a.shape # (15,)
np.expand_dims(a,axis = 0).shape # (1,15) This will make 1D array a to 2D
np.expand_dims(a,axis = 1).shape # (15,1)

np.where()

This function returns the indices of elements in an input array where the given condition is satisfied.

a = np.array([3, 92, 19, 50, 71, 89, 19, 81, 18, 21, 61, 70, 24, 20, 50])
np.where(a > 50) # output --> (array([ 1,  4,  5,  7, 10, 11]),)
np.where(a > 50, 0, a) # we can also replace those values
# output ---> array([ 3,  0, 19, 50,  0,  0, 19,  0, 18, 21,  0,  0, 24, 20, 50])

np.argmax() and np.argmin()

This method returns indices of the max/min element of the array in a particular axis.

a = np.array([3, 92, 19, 50, 71, 89, 19, 81, 18, 21, 61, 70, 24, 20, 50])
np.argmax(a) # output ----> 1 (92 at index pos: 1 is maximum)
np.argmin(a) # output ----> 0

b = np.array([[99, 90, 90, 36],
       [46, 65, 38, 51],
       [41, 91, 90, 42],
       [ 1, 46,  6, 98],
       [99, 12, 99, 49],
       [14, 82, 69, 62]])

np.argmax(b, axis = 0) # output --> array([0, 2, 4, 3])
np.argmax(b, axis = 1) # output --> array([0, 1, 1, 3, 0, 1])

np.cumsum()

This function is used when we want to compute the cumulative sum of array elements over a given axis.

# Using previous a and b arrays:
np.cumsum(a) 
# output: array([  3,  95, 114, 164, 235, 324, 343, 424, 442, 463, 524, 594, 618, 638, 688])
np.cumsum(b,axis=1)
# output: array([[ 99, 189, 279, 315],
      # [ 46, 111, 149, 200],
      # [ 41, 132, 222, 264],
      # [  1,  47,  53, 151],
      # [ 99, 111, 210, 259],
      # [ 14,  96, 165, 227]])

np.percentile()

Used to compute the nth percentile of the given data (array elements) along the specified axis.

# Using previous a and b arrays:
print(np.percentile(a,50)) # output 50.0
print(np.percentile(a,100)) # output 92.0

np.histogram()

Computes the frequency distribution of data by dividing it into bins and returns a tuple of two NumPy arrays:

  • The first array contains the counts (frequencies) of data points in each bin.

  • The second array contains the bin edges, the boundaries that define the range of each bin (including the rightmost edge).

a = np.array([3, 92, 19, 50, 71, 89, 19, 81, 18, 21, 61, 70, 24, 20, 50])
np.histogram(a,bins = [0,50,100]) 
# Output: (array([7, 8]), array([  0,  50, 100]))

np.isin()

With the help of numpy.isin() method, we can see that one array having values are checked in a different numpy array having different elements with different sizes.

a = np.array([3, 92, 19, 50, 71, 89, 19, 81, 18, 21, 61, 70, 24, 20, 50])
items = [10,20,30,40,50,60,70,80,90,100] # we can also provide single value
a[np.isin(a,items)] # it will return array of those elements which are same in both
# Output: array([50, 70, 20, 50])

np.flip()

Reverses the order of array elements along the specified axis, preserving the shape of the array.

np.flip(a) # output: array([50, 20, 24, 70, 61, 21, 18, 81, 19, 89, 71, 50, 19, 92,  3])
np.flip(b,axis = 1) # this will reverse the each row of 2d array b. 
np.flip(b) # this will reverse the whole array along both row-wise and col-wise.

np.delete()

The numpy.delete() function returns a new array with the deletion of sub-arrays along with the mentioned axis.

a = np.array([110, 530,  28,  50,  38,  37,  94,  92,   5,  30,  68,   9,  78, 2,  21])
np.delete(a,[0,2,4])
# Output: array([530,  50,  89,  19,  81,  18,  21,  61,  70,  24,  20,  50])

np.clip()

numpy.clip() function is used to Clip (limit) the values in an array.

a = np.array([110, 530,  28,  50,  38,  37,  94,  92,   5,  30,  68,   9,  78, 2,  21])
np.clip(a,a_min = 25, a_max = 75)
# Output: array([75, 75, 25, 50, 71, 75, 25, 75, 25, 25, 61, 70, 25, 25, 50])

np.repeat() and np.tile()

  • Repeat each element of an array after themselves.

  • Repeat the whole array multiple times.

# np.repeat 
arr = np.array([1,2,3])
np.repeat(arr,3) # output: array([1, 1, 1, 2, 2, 2, 3, 3, 3])

# np.tile
arr = np.array([1,2,3])
np.tile(arr,3) # output: array([1, 2, 3, 1, 2, 3, 1, 2, 3])

๐Ÿ“š Bonus Resource

๐Ÿ‘‰ Before diving into the conclusion, I invite you to explore my GitHub repository:
๐Ÿ”— NumPy Basic to Advanced: https://github.com/ShehrazSarwar/NumPy-Basic-to-Advanced-

This repository offers a comprehensive journey from basic to advanced NumPy concepts, complete with tasks designed for real-world applications.
It's a valuable resource for anyone looking to master NumPy efficiently.

Conclusion

By mastering these essential NumPy methods, you can significantly enhance your ability to manipulate arrays efficiently. These techniques not only streamline your coding process but also empower you to tackle complex data tasks with ease. Embrace these tools to make your NumPy experience more productive and enjoyable, and continue exploring the vast capabilities of this powerful library.

0
Subscribe to my newsletter

Read articles from Shehzified directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shehzified
Shehzified

I'm Shehraz Sarwar, a CS student at IUGC and Silver Medalist from FAST. I love blending code with creativity, exploring Python, Data Science, AI, and the real-world magic of math. With a strong base in Python and Data Analysis, along with C, C++, and Java, I tackle problems through hands-on projects. Beyond code, I dive into video editing, 3D art, and UI/UX design, fueling my journey to become a versatile Computer Scientist.