NumPy - Methods to Create Arrays

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:

>>> import numpy as np
>>> np.zeros(6)
array([ 0.,  0.,  0.,  0.,  0.,  0.])
>>> np.zeros([2,3])
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> np.ones([3,3])
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>>

Function zeros_like() and ones_like()

The zeros_like() and ones_like() functions create a new array with the same dimensions and type of an existing one:

>>> a = np.array([[1, 2, 3], [4, 5, 6]], float)
>>> np.zeros_like(a)
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> np.ones_like(a)
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>>

Function np.arrange()

The arrange function is similar to the range function but returns an array. It returns evenly spaced values within a given interval.

Here is the general form:

np.arrange(start, stop=None, step=1, dtype=None)
  • start: The first value in the sequence.

  • stop: The limiting value: the last element of the sequence will never be greater than or equal to this value.

    >>> print np.arrange(1.0, 4.0)
    [ 1.  2.  3.]
    

    If you omit the stop value, you will get a sequence starting at zero and using start as the limiting value.

    >>> print np.arrange(4)
    [0 1 2 3]
    
  • step: The common difference between successive values of the array. The default value is one.

    >>>np.arrange(0, 1, 0.2)
    [ 0. , 0.2, 0.4, 0.6, 0.8]
    
  • dtype: Use this argument to force representation using a specific type.

    >>> print np.arrange(10)
    [0 1 2 3 4 5 6 7 8 9]
    >>> print np.arrange(10, dtype=np.float_)
    [ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
    

Related Downloads

Membership
Learn the skills required to excel in data science and data analytics covering R, Python, machine learning, and AI.
I WANT TO JOIN
JOIN 30,000 DATA PROFESSIONALS

Free Guides - Getting Started with R and Python

Enter your name and email address below and we will email you the guides for R programming and Python.

Saylient AI Logo

Take the Next Step in Your Data Career

Join our membership for lifetime unlimited access to all our data analytics and data science learning content and resources.