How To Create Numpy Array & Range Array With Examples

This article will tell you how to use the Python NumPy module to create a NumPy Ndarray array and how to create an array with a range of data.

1. array().

  1. This is the basic function that can create a NumPy ndarray object.
    import numpy as np
    
    def create_ndarray():
        
        array = np.array(['python', 'java', 'javascript'])
        
        print(array)
    
    
    
    if __name__ == '__main__':
        
        create_ndarray()
  2. Below is the above example source code output.
    ['python' 'java' 'javascript']

2. asarray().

  1. The asarray() function is similar to array(), but it is simpler than array(). asarray() can convert a python sequence into a ndarray object.
  2. Below is the syntax format of asarray().
    numpy.asarray(sequence,dtype = None ,order = None )
    
    sequence: Accept a python sequence, which can be a list or tuple.
    
    dtype : Optional parameter, the data type of the array.
  3. Below is an example of asarray().
    import numpy as np
    
    def create_ndarray():
        
        array = np.asarray(['python', 'java', 'javascript'])
        
        print(array)
        
        array1 = np.asarray([['python', 'java', 'javascript'], [1, 2, 3, 4, 5, 6]], order = 'F')
        
        print(array1)
    
    
    
    if __name__ == '__main__':
        
        create_ndarray()
  4. Below is the above source code execution output.
    ['python' 'java' 'javascript']
    C:\Users\zhaosong\anaconda3\lib\site-packages\numpy\core\_asarray.py:102: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
      return array(a, dtype, copy=False, order=order)
    [list(['python', 'java', 'javascript']) list([1, 2, 3, 4, 5, 6])]

3. empty().

  1. Create an uninitialized array, you can specify the shape and data type of the array.
  2. Below is the empty() method syntax format.
    numpy.empty(shape, dtype = float, order = 'C')
    
    shape: Specifies the shape of the array.
    
    dtype: The data type of the array element. The default data type is float.
    
    order: The storage order of array elements in computer memory. The default order is "C" (row priority)
  3. Below is an example.
    import numpy as np
    
    def create_ndarray():
     
        # create an empty array, the array element data type is float.
        array = np.empty((2,6), dtype = float)
        
        # print out the array object.
        print(array) 
        
        # print out the array shape.
        print(array.shape)
        
        # print out the array dimension.
        print(array.ndim)
    
    if __name__ == '__main__':
        
        create_ndarray()
  4. When you run the above example source code, you will get the below output. We can see that the empty NumPy array is not empty, it will be filled with some random float type numbers, but these values have no practical significance.
    [[1.05700345e-307 1.33514617e-307 1.11258277e-307 8.34425190e-308
      8.34423917e-308 1.00132398e-307]
     [8.90071984e-308 1.39071190e-307 1.15707032e-306 8.01058505e-307
      1.69111996e-306 9.34611148e-307]]
    (2, 6)
    2

4. frombuffer().

  1. This function will create an array using the specified buffer.
  2. The syntax format of this function is given below.
    numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
    
    buffer: Converts any object into a stream and reads it into a buffer.
    
    dtype: Returns the data type of the array. The default data type is float32.
    
    count: The number of data to be read. The default value is - 1, indicating that all data will be read.
    
    offset: The starting position of the data in the buffer. The default value is 0.
  3. Below is the example python source code.
    import numpy as np
    
    def create_ndarray():
        
        # define a string variable.
        str = b'I Love Python' 
    
        # print the string variable data type.
        print(type(str))
        
        # read the string variable data to a numpy array.
        array = np.frombuffer(str, dtype = "S1")
        
        # print out the array.
        print(array) 
        
        # print the array object type.
        print(type(array)) 
    
    if __name__ == '__main__':
        
        create_ndarray()
  4. Below is the above example execution output.
    <class 'bytes'>
    [b'I' b' ' b'L' b'o' b'v' b'e' b' ' b'P' b'y' b't' b'h' b'o' b'n']
    <class 'numpy.ndarray'>

5. fromiter().

  1. This method can convert the iterative object into a ndarray object, and its return value is a one-dimensional array.
  2. Below is it’s syntax format.
    numpy.fromiter(iterable, dtype, count = -1)
    
    iterable: Iteratable object.
    
    dtype: The element data type of the returned array.
    
    count : The number of data that will be read. The default value is -1 which means read all the data.
  3. Below is the example source code.
    import numpy as np
    
    def create_ndarray():  
        
        # invoke the range function to create a list.
        list=range(10)
        
        print('list = ', list)
    
        # convert the list object to an iterative object.
        i=iter(list)
        
        print('i = ', i)
    
        # create the numpy array object from the above iterative object.
        array=np.fromiter(i, dtype='S1')
        
        # print out the numpy array object.
        print('array = ', array)
    
    if __name__ == '__main__':
        
        create_ndarray()
  4. Below is the above example code execution result.
    list =  range(0, 10)
    i =  <range_iterator object at 0x000001E0438332B0>
    array =  [b'0' b'1' b'2' b'3' b'4' b'5' b'6' b'7' b'8' b'9']

6. ones().

  1. Returns a new array of the specified shape size and data type, and each element in the new array is filled with 1.
  2. Below is the ones() method syntax format.
    numpy.ones(shape, dtype = None, order = 'C')
  3. Below is the example source code.
    import numpy as np
    
    def create_ndarray():
        
        # create a 2 dimension array with 3 elements and each element contains 2 elements.
        array = np.ones((3,2), dtype = int) 
        
        # print out the array object.
        print(array)
        
        # print out the array object's dimension.
        print(array.ndim)
    
    if __name__ == '__main__':
        
        create_ndarray()
  4. Below is the above source code execution result.
    [[1 1]
     [1 1]
     [1 1]]
    2
    

7. zeros().

  1. This function is used to create an array whose elements are all 0. At the same time, it can also specify the shape of the array.
  2. The syntax format is as follows.
    numpy. zeros(shape,dtype=float,order="C")
    
    shape: Specifies the shape of the array.
    
    dtype: Optional, the data type of the array.
    
    order : "C" means stored in row order, "F" means stored in column order.
  3. Below is the example source code.
    import numpy as np
    
    def create_ndarray():
    
        # create a 6 elements array with the default data type (float).
        a=np.zeros(6)
    
        # print out the above object.
        print(a)
    
        # create another array with 6 elements, and the element data type is complex64.
        b=np.zeros(6,dtype="complex64" )
    
        # print out the second numpy array object.
        print(b)
    
    if __name__ == '__main__':
        
        create_ndarray()
  4. Below is the result when you run the above source code.
    [0. 0. 0. 0. 0. 0.]
    [0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j]

8. arange().

  1. The arange() function can be used to create an array with a given range of values. The syntax format is as follows.
    numpy.arange(start, stop, step, dtype)
    
    start: The beginning value is 0 by default.
    
    stop The ending value. Note that the generated array element value can not contain the ending value.
    
    step: Step size, default is 1.
    
    dtype : Optional parameter that specifies the data type of the ndarray array.
    
  2. The following example will generate a ndarray according to the range specified by start and stop and the step value.
    import numpy as np
    
    def create_ndarray():
         
        # create a default range array start from 0, ends with 10, the step is 1.
        array = np.arange(10)
        
        print(array)
        
        # create a range array with the provided start, stop, step 
        array1 = np.arange(10,20,2) 
        
        print (array1)
    
    if __name__ == '__main__':
        
        create_ndarray()
  3. Below is the above example execution result.
    [0 1 2 3 4 5 6 7 8 9]
    [10 12 14 16 18]
    

9. linspace().

  1. This method will return a one-dimensional isometric array within the specified value range. Below is its syntax format.
    np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
    
    start: Starting value of the number range.
    
    stop: Ending value of the number range.
    
    num: How many elements will be generated in this numerical range. The default value is 50.
    
    endpoint: The default value is true, which means that the array contains the stop number, if set to false, the array will not include the stop number value.
    
    retstep: The default value is false, which means that the step value will not be displayed in the generated array; otherwise, it will be displayed.
    
    dtype : Represents the data type of the array element value.
  2. Below is an example of the linspace() method.
    import numpy as np
    
    def create_ndarray():
        
        # the start number is 0, the end number is 60, there are 5 elements in the array, and it will show the step value( the number between 2 elements).
        array = np.linspace(start = 0, stop = 60, num = 5, retstep=True)
        
        print(array)
        
        # the start number is 0, the end number is 60, there will have 20 elements in the array, and it will not show the step value( the number between 2 elements).
        array = np.linspace(start = 0, stop = 60, num = 20, endpoint=False, dtype=int)
        
        print(array)
    
    if __name__ == '__main__':
        
        create_ndarray()
  3. Below is the above python source code execution result.
    (array([ 0., 15., 30., 45., 60.]), 15.0)
    [ 0  3  6  9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57]
    

10. logspace().

  1. This function also returns a ndarray, which is used to create a proportional array. The syntax format is as follows.
    np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
    
    start: Starting value of the array, base**start power.
    
    stop: Ending value of the array, base**stop power.
    
    num: The number of sample numbers in the range of values, it is 50 by default.
    
    endpoint: The default value is true, which means the array will include the ending value; otherwise, it does not.
    
    base: The log base of the logarithmic function. The default value is 10.
    
    dtype: Optional parameter that specifies the data type of the ndarray elements.
  2. Below is the logspace() function example.
    import numpy as np
    
    def create_ndarray():
          
        # the start number is 10**1, the end number is 10**2, it will create 10 numbers in the array. 
        array = np.logspace(start=1.0, stop=2.0, num = 10)
        
        print (array)
        
        # the start number is 3**1, the end number is 3**2, it will create 6 numbers in the array, the log base number is 3. 
        array = np.logspace(start=1.0, stop=2.0, base=3, num = 6)
        
        print (array)
    
    if __name__ == '__main__':
        
        create_ndarray()
  3. Below is the above example execution result.
    [ 10.          12.91549665  16.68100537  21.5443469   27.82559402
      35.93813664  46.41588834  59.94842503  77.42636827 100.        ]
    
    [3.         3.73719282 4.65553672 5.79954613 7.22467406 9.        ]

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky