In addition to using array() function that passes a list or tuple to generate an Numpy array in Python, there are lots of ready-made functions that make it possible to generate large size Numpy arrays in Python. Following code examples show some of the most common functions in that respect.
#import Numpy module
import numpy as np
#zeros() function create array with all element zero
np.zeros((6,9))
#output
array([[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0.]])
#ones() function generates array with all element one
np.ones((6,9))
#result
array([[1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1., 1., 1.]])
#arange() generate sequences of number, with the starting
#index included, ending index not included. Default gap 1
np.arange(3, 19)
#result
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])
#arange() with gap 2
np.arange(3, 19, 2)
#result
array([ 3, 5, 7, 9, 11, 13, 15, 17])
#arange() with fraction gap
np.arange(3, 19, 0.9)
#result
array([ 3. , 3.9, 4.8, 5.7, 6.6, 7.5, 8.4, 9.3, 10.2, 11.1, 12. ,
12.9, 13.8, 14.7, 15.6, 16.5, 17.4, 18.3])
#combination of arange() and reshape() to generate a two-dimensional
#array
np.arange(3, 19).reshape(2, 8)
#result
array([[ 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18]])
#linspace() create array with specified elements between
#starting and ending index
#an array of 8 items between 10 and 100, with equal distance
#from each other
np.linspace(10, 100, 8)
#result
array([ 10. , 22.85714286, 35.71428571, 48.57142857,
61.42857143, 74.28571429, 87.14285714, 100. ])
#random() generates specified size of random numbers between 0 and 1
np.random.random(32)
#result
array([0.51092275, 0.89845 , 0.89418208, 0.25598389, 0.49376735,
0.80426067, 0.51799277, 0.12338302, 0.40691178, 0.06597121,
0.74520068, 0.92515965, 0.62996679, 0.95935245, 0.27515135,
0.82625264, 0.13453611, 0.12805922, 0.30203039, 0.72715859,
0.7394496 , 0.02885726, 0.06150057, 0.15784562, 0.70198207,
0.86898905, 0.29640531, 0.83211344, 0.77473149, 0.42414732,
0.26098734, 0.72941855])
0 Comments