Once you've installed NumPy you can import it as a library:
#Import library numpy and defined them with alias np
import numpy as np
# Creating a list with name my_list
my_list = [1,2,3]
my_list
#Convert this list into array
np.array(my_list)
Matrix are 2D array so we can try to crate array with the help ofmatrix out
# Define matrix first
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
my_matrix
#Convert defined matrix with the np.array function
np.array(my_matrix)
There are lots of built-in ways to generate Arrays
This function returns an ndarray object containing evenly spaced values within a given range. The format of the function is as follows
numpy.arange(start, stop, step, dtype)
np.arange(0,10)
np.arange(0,11,2)
Generate arrays of zeros or ones
#Create array with 0
np.zeros(3)
np.zeros((5,5))
# Create array with 1
np.ones(3)
np.ones((3,3))
This function is similar to arange() function. In this function, instead of step size, the number of evenly spaced values between the interval is specified. The usage of this function is as follows −
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
np.linspace(0,10,3)
np.linspace(0,10,50)
np.random.rand(2)
np.random.rand(5,5)
Return a sample (or samples) from the "standard normal" distribution. Unlike rand which is uniform:
np.random.randn(2)
np.random.randn(5,5)
Return random integers from low
(inclusive) to high
(exclusive).
np.random.randint(1,100)
np.random.randint(1,100,10)
Let's discuss some useful attributes and methods or an array:
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
arr
ranarr
Returns an array containing the same data with a new shape.
arr.reshape(5,5)
These are useful methods for finding max or min values. Or to find their index locations using argmin or argmax
ranarr
#gives the max value
ranarr.max()
#Gives the index position of max value
ranarr.argmax()
#gives the minimum value
ranarr.min()
#Gives the index position of min value
ranarr.argmin()
Shape is an attribute that arrays have (not a method)
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.
# Vector
arr.shape
arr.reshape(1,25).shape
An object describing the type of the elements in the array. One can create or specify dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.
arr.dtype