12 Basic Commands with NumPy Array



NumPy (pronounced as Num-pee or Num-pai) is one of the important python packages (other being SciPy) for scientific computing. NumPy offers fast and flexible data structures for multi-dimensional arrays and matrices with numerous mathematical functions/operations associated with it. Core data structure in NumPy is “ndarray”, short for n-dimesional array for storing numeric values. Let us get started with some basic commands with NumPy 1d-array (one-dimensional array).

How to import NumPy package?

# import numpy package with nickname "np"
>import numpy as np
>%>%

How to create a one-dimensional array?

# create a numpy array
>my_first_array = np.array([1, 2, 3,4,5])
>my_first_array
array([1, 2, 3, 4, 5])

How to find the length (or number of elements) of a 1d-array?

# length of the array
>len(my_first_array)
5

How to sum all the elements in 1d-array?

# sum of all elements in the array
>np.sum(my_first_array)
>my_first_array.sum()
15

How to find the maximum value in NumPy 1d-array?

# maximum value the elements in the array
>np.max(my_first_array)
>my_first_array.max()
5

How to find the minimum value in NumPy 1d-array?

# minimum value the elements in the array
>np.min(my_first_array)
>my_first_array.min()
1

How to create NumPy 1d-array with 1s?

# create a numpy array of 1s (of length 5)
>np.ones(5)
array([ 1.,  1.,  1.,  1.,  1.])

How to create empty NumPy 1d-array of specified length?

# create an empty numpy array of length 5
>np.empty(5)
array([  1.49166815e-154,   1.49166815e-154,   3.03574399e-152,
         2.64522460e+185,   1.45913207e-152])

How to create NumPy 1d-array with 0s?

# create a numpy array of length 5 with 5 zeros
>np.zeros(5)
array([ 0.,  0.,  0.,  0.,  0.])

How to create NumPy 1d-array with a range of numbers?

# create a numby array with a range of numbers 0 to 9
>np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# create a numpy array with a range of numbers and step size
>np.arange(0, 9, 2)
array([0, 2, 4, 6, 8])

How to create NumPy 1d-array with random numbers?

# create an array with random numbers
>np.random.random(5)
array([ 0.4648749 ,  0.9236576 ,  0.93804724,  0.86871356,  0.49829188])

How to create NumPy 1d-array with equally spaced numbers in an interval?


Return evenly spaced numbers over a specified interval.
>np.linspace(0, 1, 10)
array([ 0.        ,  0.11111111,  0.22222222,  0.33333333,  0.44444444,
        0.55555556,  0.66666667,  0.77777778,  0.88888889,  1.        ])