/    /  NumPy – Arrays

NumPy – Arrays:

In this tutorial, we will discuss about arrays in Numpy.

In NumPy, Array is an Object class little similar to lists in Python. But, here the array holds the elements which are same numeric data type like int or float.

This array object can process the large numeric data efficiently when compared to lists.

Below is the sample examples of creating an array.

Creating an One-Dimensional(1-D) Array:

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

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

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

>>> a
array([1, 2, 3, 4])

>>> type(a)
<class 'numpy.ndarray'>

# ndim will be used to find the type of dimension of that array.

>>> a.ndim
1

# shape property will be used to find out the size of each array dimension

>>> a.shape
(4,)

# len function will be used to get the length of first array axis in the dimension

>>> len(a)
4

Arrays are Multi-dimensional (mostly like Matrices in Mathematics) and let us see creating an Two-Dimensional(2-D) Array:

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

>>> b
array([[1, 2, 3, 4],
[5, 6, 7, 8]])

>>> type(b)
<class 'numpy.ndarray'>

>>> b.ndim
2

>>> b.shape
(2, 4)

>>> len(b)
2

Creating an Three-Dimensional(3-D) Array:

>>> c=np.array([[1,2,3,4],[5,6,7,8],[9,8,7,6]],int)

>>> type(c)
<class 'numpy.ndarray'>

>>> c
array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 8, 7, 6]])

>>> c.ndim
2

>>> c.shape
(3, 4)

>>> len(c)
3

Accessing the values in above three-Dimensional Array:

>>> c[1,1]
6

>>> c[2,3]
6

>>> c[2,0]
9

We can reshape an array using the reshape function.

>>> c.reshape(4,3)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[8, 7, 6]])