NumPy - Methods to Create Arrays

Premium

We learned about how to create an array using np.array(). NumPy also provides a few other methods to create new arrays.

Functions np.zeros() and np.ones()

The functions zeros and ones create new arrays of specified dimensions filled with these values (Os and 1s). These are perhaps the most commonly used functions to create new arrays:

1>>> import numpy as np
2>>> np.zeros(6)
3array([ 0.,  0.,  0.,  0.,  0.,  0.])
4>>> np.zeros([2,3])
5array([[ 0.,  0.,  0.],
6       [ 0.,  0.,  0.]])
7>>> np.ones([3,3])
8array([[ 1.,  1.,  1.],
9       [ 1.,  1.,  1.],
10       [ 1.,  1.,  1.]])
11>>>
12

Unlock Premium Content

Upgrade your account to access the full article, downloads, and exercises.

You'll get access to:

  • Access complete tutorials and examples
  • Download source code and resources
  • Follow along with practical exercises
  • Get in-depth explanations