Python NumPy Tutorial – NumPy ndarray & NumPy Array

Free Python course with 25 real-time projects Start Now!!

In our last Python Library tutorial, we studied Python SciPy. Now we are going to study Python NumPy.

In this NumPy tutorial, we are going to discuss the features, Installation and NumPy ndarray.

Moreover, we will cover the data types and array in NumPy. So, let’s begin the Python NumPy Tutorial.

Python NumPy Tutorial - NumPy ndarray & NumPy Array

Python NumPy Tutorial – NumPy ndarray & NumPy Array

What is NumPy?

A library for Python, NumPy lets you work with huge, multidimensional matrices and arrays.

Along with that, it provides a gamut of high-level functions to perform mathematical operations on these structures.

Here is a short brief about it:

  • Author- Travis Oliphant
  • First Release- 1995 (Released as Numeric; Changed to NumPy in 2006)
  • Stable Release- June, 2018
  • Written in- Python Programming, C

Python NumPy is cross-platform and BSD-licensed. We often use it with packages like Matplotlib and SciPy.

This can be seen as an alternative to MATLAB. The term ‘Numpy’ is a portmanteau of the words ‘NUMerical’ and ‘PYthon’.

Numpy Tutorial – Features of Numpy

In this Python NumPy Tutorial, we are going to study the feature of NumPy:

  • NumPy stands on CPython, a non-optimizing bytecode interpreter.
  • Multidimensional arrays.
  • Functions and operators for these arrays.
  • Python Alternative to MATLAB.
  • ndarray- n-dimensional arrays.
  • Fourier transforms and shapes manipulation.
  • Linear algebra and random number generation.

Numpy Tutorial – How to Install NumPy?

You can use pip to install numpy-

pip install numpy

Then you can import it as-

>>> import numpy as np

Numpy Tutorial – NumPy ndarray

This is one of the most important features of numpy. ndarray is an n-dimensional array, a grid of values of the same kind.

A tuple of nonnegative integers indexes this tuple. An array’s rank is its number of dimensions.

Let’s take a few examples.

>>> a=np.array([1,2,3])
>>> type(a)

Output

<class ‘numpy.ndarray’>

>>> a.shape

Output

(3,)
>>> a[0],a[2]

Output

(1, 3)
>>> a[1]=5
>>> a

Output

array([1, 5, 3])

As you can see, the array’s shape is (3,). What happens when we build an array of more than one dimension?

Let’s see.

>>> b=np.array([[2,7,9],[5,1,3]])
>>> b

Output

array([[2, 7, 9],
[5, 1, 3]])
>>> b[0,1]

Output

7
>>> b.shape

Output

(2, 3)
>>> b.size

Output

6

1. How to Create NumPy Array?

The following lines of code create a few more arrays:

>>> np.arange(7) #This is like range in Python

Output

array([0, 1, 2, 3, 4, 5, 6])
>>> np.random.random((3,3)) #Fills in random values

Output

array([[0.56074267, 0.67303599, 0.65973007],
[0.37222497, 0.13230271, 0.40858618],
[0.74455771, 0.52119999, 0.6927821 ]])
>>> np.ones((2,3))

Output

array([[1., 1., 1.],
[1., 1., 1.]])
>>> np.zeros((1,2))

Output

array([[0., 0.]])
>>> np.eye(3) #Identity matrix

Output

array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> np.full((3,2),7) #Matrix of constants

Output

array([[7, 7],
[7, 7],
[7, 7]])
>>> np.linspace(1,2,4) #4 values spaced evenly between, and including, 1 and 2.

Output

array([1. , 1.33333333, 1.66666667, 2. ])
>>> np.empty([2,3]) #Empty array

Output

array([[1., 0., 3.],
[0., 4., 0.]])

2. Some Parameters

>>> np.array([1,3,4],ndmin=3) #Minimum dimension

Output

array([[[1, 3, 4]]])
>>> np.array([1,3,4],dtype=complex) #Data type

Output

array([1.+0.j, 3.+0.j, 4.+0.j])

Numpy Tutorial – Data Types

As we’ve said before, a NumPy array holds elements of the same kind.

If while creating a NumPy array, you do not specify the data type, NumPy will decide it for you.

We have the following data types-

bool_, int_, intc, intp, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float_, float16, float32, float64, complex_, complex64, complex128

We can confirm:

>>> np.dtype(np.int32)

Output

dtype(‘int32’)
>>> np.dtype('i4')

Output

dtype(‘int32’)
>>> np.dtype('i8')

Output

dtype(‘int64’)

Functions of NumPy Array

Let’s take a look at all that we can do to an array and what more we can find out about it.

>>> a=np.array([[1,2,3],[4,5,6]])
>>> a.reshape(3,2)

Output

array([[1, 2],
[3, 4],
[5, 6]])
>>> a.ndim #Number of array dimensions

Output

2
>>> np.array([[1,2,3],[4,5,6]]).itemsize #Length of each element in bytes

Output

4
>>> np.array([[1,2,3],[4,5,6]],dtype=np.int8).itemsize

Output

1
>>> a

Output

array([[1, 2, 3],
[4, 5, 6]])
>>> a.flags

Output

C_CONTIGUOUS: True
F_CONTIGUOUS: False
OWNDATA: True
WRITEABLE: True
ALIGNED: True
WRITEBACKIFCOPY: False
UPDATEIFCOPY: False

Numpy Array Indexing

It is possible to slice you NumPy arrays- with multiple slices for multidimensional arrays.

>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> b=a[:2,1:3]
>>> b

Output

array([[2, 3],
[5, 6]])
>>> a[1,2]

Output

6
>>> b[0,0]=79
>>> a

Output

array([[ 1, 79, 3],
[ 4, 5, 6],
[ 7, 8, 9]])

As you can see, changes to a slice modify an original.

>>> a[1,:]

Output

array([4, 5, 6])
>>> a[1:2,:]

Output

array([[4, 5, 6]])
>>> a[:,1]

Output

array([79, 5, 8])
Python NumPy Tutorial - NumPy Array Index

Python NumPy Tutorial – NumPy Array Index

1. Integer Indexing

It is possible to create an array from another.

>>> a=np.array([[1,2],[3,4],[5,6]])
>>> a[[0,1,2],[0,1,0]] #Prints elements at [0,0], [1,1], and [2,0]

Output

array([1, 4, 5])

Let’s pick elements-

>>> a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
>>> b = np.array([0, 2, 0, 1])
>>> b

Output

array([0, 2, 0, 1])
>>> a[np.arange(4), b]

Output

array([ 1, 6, 7, 11])
>>> a[np.arange(4), b]+=10
>>> a

Output

array([[11, 2, 3],
[ 4, 5, 16],
[17, 8, 9],
[10, 21, 12]])

2. Boolean Indexing

This will let you pick elements that satisfy a condition.

>>> a=np.array([[1,2],[3,4],[5,6]])
>>> boolean=(a>3)
>>> boolean

Output

array([[False, False],
[False, True],
[ True, True]])
>>> a[boolean]

Output

array([4, 5, 6])

Mathematical Functions on Arrays in NumPy

Let’s now look at some mathematical functions to call on arrays.

>>> a=np.array([[1,2,3],[4,5,6]])
>>> b=np.array([[7,8,9],[10,11,12]])
>>> np.add(a,b) #a+b does the same

Output

array([[ 8, 10, 12],
[14, 16, 18]])
>>> np.subtract(a,b) #Same as a-b

Output

array([[-6, -6, -6],
[-6, -6, -6]])
>>> np.multiply(a,b) #a*b works too

Output

array([[ 7, 16, 27],
[40, 55, 72]])
>>> np.divide(a,b) #Same as a/b

Output

array([[0.14285714, 0.25 , 0.33333333],
[0.4 , 0.45454545, 0.5 ]])
>>> np.sqrt(a) #Produces square root

Output

array([[1. , 1.41421356, 1.73205081],
[2. , 2.23606798, 2.44948974]])
>>> a=np.array([[1,2],[3,4]])
>>> np.sum(a)

Output

10
>>> np.sum(a,axis=0) #Sum of each column

Output

array([4, 6])
>>> np.sum(a,axis=1) #Sum of each row

Output

array([3, 7])

To transpose this matrix:

>>> a.T

Output

array([[1, 3],
[2, 4]])
>>> np.array([1,3,2]).T #NOP

Output

array([1, 3, 2])

Some functions that operate on a larger context-

>>> x=np.array([[1,2],[3,4]])
>>> y=np.array([[5,6],[7,8]])
>>> v=np.array([9,10])
>>> w=np.array([11,12])
>>> v.dot(w) #Same as np.dot(v,w)

Output

219
>>> x.dot(v)

Output

array([29, 67])
>>> x.dot(y)

Output

array([[19, 22],
[43, 50]])

So, this was all about Python NumPy Tutorial. Hope you like our explanation.

Python Interview Questions on NumPy

  1. What is Python NumPy array?
  2. What is the purpose of NumPy in Python?
  3. What is the difference between Pandas and NumPy in Python?
  4. How does NumPy work in Python?
  5. What functions does NumPy provide in Python?

Conclusion

Hence, in this Python NumPy Tutorial we studied, how to install NumPy, NumPy ndarray.

In addition, we discussed NumPy Array with its Functions and data types. This sums it up for NumPy.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook

5 Responses

  1. birajdar pintu says:

    Thanku sir as compare to other tutorial your tutorial easily understand definately anyone student read

    • DataFlair Team says:

      Hi Birajdar,
      We feel motivated when our loyal reader appriciate the efforts, we made in our every Python tutorial. Hope, you are exploring other Python articles.
      Do share with your peer groups.
      Regards,
      DataFlair

  2. remya says:

    step no 8 , should it be a[0, 1] = 79 , in order to get [[ 1 79 3]
    [ 4 5 6]
    [ 7 8 9]] as an output ?

    • DataFlair Team says:

      Hi Remya,
      Thanks for the comment on Python Numpy Tutorial. Changing that value in b also changes it for a, since both points to the same object.
      Hope, now you get it.
      Regards,
      DataFlair

  3. kishan yadav says:

    i am getting this kind of error how to resolve this
    import sklearn
    Traceback (most recent call last):
    File “”, line 1, in
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\__init__.py”, line 64, in
    from .base import clone
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\base.py”, line 11, in
    from scipy import sparse
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\__init__.py”, line 231, in
    from .csr import *
    File “C:\Users\kishan yadav\AppData\Local\Programs\Python\Python37\lib\site-packages\scipy\sparse\csr.py”, line 15, in
    from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \
    ImportError: DLL load failed: The specified module could not be found.
    >>> from .base import clone
    Traceback (most recent call last):
    File “”, line 1, in
    ModuleNotFoundError: No module named ‘__main__.base’; ‘__main__’ is not a package
    >>> pip install clone

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.