DEV Community

Cover image for NumPy Unleashed: Exploring the Power of Special Arrays
Lohith
Lohith

Posted on • Edited on

NumPy Unleashed: Exploring the Power of Special Arrays

In the NumPy library, we have the capability to generate a variety of specialized arrays. These include arrays filled with zeros, ones, or even uninitialized arrays, among others.

1. Array with zeros:-

NumPy has the zeros() function to create an n-D array.The zeros() function is quite versatile and can be used to create multi dimensional arrays of any size, all initialized to zero.

Example:-

import numpy as np

# Create a 2-D array of size 3x4 filled with zeros
zero_array = np.zeros((3, 4))

print(zero_array)
Enter fullscreen mode Exit fullscreen mode
Output:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
Enter fullscreen mode Exit fullscreen mode

2. Array with ones

Numpy has the ones() function to create an n-D array.The ones() function is very useful when you need to create a multi dimensional array of any size, all initialized to one. It’s a great tool for initializing weights in machine learning algorithms, among other uses.

import numpy as np

# Create a 2-D array of size 3x4 filled with ones
ones_array = np.ones((3, 4))

print(ones_array)

Enter fullscreen mode Exit fullscreen mode
Output:
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
Enter fullscreen mode Exit fullscreen mode

3. Empty array:-

NumPy provides the empty() function to generate an n-dimensional array. This function differs from the zeros() function. Specifically, the zeros() function consistently returns an array filled with zeros of the specified datatype. In contrast, the empty() function may not necessarily do so.

import numpy as np

# Create a 2-D array of size 3x4 with uninitialized values
empty_array = np.empty((3, 4))

print(empty_array)
Enter fullscreen mode Exit fullscreen mode
[[6.23042070e-307 4.67296746e-307 1.69121096e-306 9.34609111e-307]
 [1.33511290e-306 1.33511969e-306 6.23037996e-307 6.23053954e-307]
 [9.34609790e-307 8.45593934e-307 9.34600963e-307 1.86921143e-306]]
Enter fullscreen mode Exit fullscreen mode

Please note that the empty() function does not initialize the array elements to any specific values. Therefore, it can sometimes be faster than the zeros() or ones() functions if you are planning to fill the array with data later.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more