# NumPy

NumPy is a Python library and an open-source project. NumPy stands for Numeric Python. It is a fundamental package for scientific computing with Python. NumPy provides support for multidimensional arrays. NumPy is used for solving mathematical and scientific problems in Python. The NumPy module contains many mathematical functions and constants such as the base of natural logarithms e, and pi. The latest version of NumPy is NumPy v1.22.0. The latest NumPy manual can be found here.

The major features of NumPy are:

• Powerful N-dimensional array object
• Solving linear algebra, Fourier transform
• Random number generation
• Integration of C/C++ code

NumPy is not bundled with Python. So we must install NumPy by running the following command from the command line

``pip install numpy``

The main object of NumPy is a multidimensional array. An array is a collection of homogeneous data items, all of the same data type. So, we could have collection of integers or a collection of floats, or a collection of string data type or a collection of complex numbers. NumPy’s array class is called ndarray. It is also known by the alias array.

Arrays can be of dimension-1, or 2-dimensions, 3-dimensions, etc. A one-dimensional array is shown below and it has one axis:

[ 1 2 3 4]

A 2-dimensional array is shown below and it has two axes.

```[[ 1    2   3   4],
[ 2    0   1   3]]```

The concept of axis can be understood from the following diagram:

Axis 0 is along the rows (all rows lie along the axis 0. Axis 0 —> Vertical axis). Axis 1 is along the columns (all columns lie along axis 1. Axis 1 —> Horizontal axis).

Attributes of ndarray object:

The important attributes (properties) of an ndarray object are:

ndarray.ndim : Gives the number of axes (dimensions) of the array

ndarray.shape: Gives the dimensions of the array. For an array with n rows and m columns, shape will be (n, m). The length of the shape tuple is the number of axes, ndim.

ndarray.size: Gives the total number of elements of the array. This is equal to the product of the elements (n x m).

ndarray.dtype: Gives an object describing the type of the elements in the array. Standard Python data types can be used. NumPy also provides data types of its own. numpy.int32, numpy.int16, and numpy.float64 are some examples.

ndarray.itemsize : Gives the size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8).

ndarray.data : It is the buffer containing the actual elements of the array. We will not need to use this attribute because we will access the elements in an array using indexing facilities.

How to get the Numpy version number?

```#Creating an array
import numpy as np
import numpy as np
print(np.__version__)

# Output is : 1.21.2
# >
```

How to Create an Array and Find Attributes of an Array?

```#Creating an array
import numpy as np

#Step 1 - Creating 1-d array
a = np.array([1, 2, 3])

#printing the array
print("1-D array: ")
print (a)

#Step 2 - Creating 2-d array
b = np.array([ [1, 2, 3],
[4, 1, 0],
[2, 7, 3]
])

print ("2-D array : ")
print(b)

#Step 3 - Attributes of an array
#ndim - no. of dimensions
print("Dim of a ", a.ndim)
print("Dim of b ", b.ndim)

#shape - no. of rows and cols
print("Shape of a ", a.shape)  #note this o/p for a strange result
print("Shape of b ", b.shape)

#size - no. of elements in array (rows x cols)
print("Size of a ", a.size)
print("Size of b ", b.size)

#dtype - datatype of the elements of the array
print("Data type of a: ", a.dtype)
print("Data type of b: ", b.dtype)

#Array of strings
print("Size of s: ", s.size)
print("Data type of s: ", s.dtype.name)  #try without writing name at end

```
```Output:
Python 3.7.2 (bundled)
%Run Numpy001.py
1-D array:
[1 2 3]
2-D array :
[[1 2 3]
[4 1 0]
[2 7 3]]
Dim of a 1
Dim of b 2
Shape of a (3,)
Shape of b (3, 3)
Size of a 3
Size of b 9
Data type of a int32
Data type of b int32
Size of s 3
Data type of s str288
%Run Numpy001.py
1-D array:
[1 2 3]
2-D array :
[[1 2 3]
[4 1 0]
[2 7 3]]
Dim of a 1
Dim of b 2
Shape of a (3,)
Shape of b (3, 3)
Size of a 3
Size of b 9
Data type of a: int32
Data type of b: int32
Size of s 3
Data type of s: str288
%Run Numpy001.py
1-D array:
[1 2 3]
2-D array :
[[1 2 3]
[4 1 0]
[2 7 3]]
Dim of a 1
Dim of b 2
Shape of a (3,)
Shape of b (3, 3)
Size of a 3
Size of b 9
Data type of a: int32
Data type of b: int32
Size of s: 3
Data type of s: str288```

How to create an array of any dimension?

```import numpy as np

arrObj = np.array([11, 22, 33, 44], ndmin = 5)

print(arrObj)
```
`[[[[[11 22 33 44]]]]]`

How to perform mathematical operations on an array?

```import numpy as np
#Math operations on arrays

#Step 1 - Creating 1-d array
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

print ("A array : ", a)
print ("B array : ", b)

#Sum of arrays
c = a + b
print ("C array : ", c)

#Diff of arrays
d = a - b
print ("D array : ", d)

#Squaring an array
sq = a ** 2
print ("Squared A array : ", sq)

#Multiply each element of array a by 4
q = 4 * np.array(a)
print ("Four times A array : ", q)

#performing trigonometric function on an array
degreeangle = np.array([0, 30, 45, 60, 90])

#calculate cosine values
print("Cosine values : ", cvalues)

#calculate tangent values
print("Tan values : ", tvalues)

```
```%Run Numpy003.py
A array : [1 2 3]
B array : [4 5 6]
C array : [5 7 9]
D array : [-3 -3 -3]
Squared A array : [1 4 9]
Four times A array : [ 4 8 12]
Cosine values : [ 1.00000000e+00 8.65991456e-01 7.07034768e-01 4.99882405e-01
-2.03673204e-04]
Tan values : [ 0.00000000e+00 5.77440794e-01 1.00020369e+00 1.73259406e+00
-4.90982594e+03]```

Changing the shape of an array

```#Resize an array
import numpy as np

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

print("Original A ")
print(a)

a.shape = (3,2)

print("New A ")
print(a)

#reshape function does similar work
c = np.array([[1,2,3],
[4,5,6]])

d = c.reshape(3, 2)
print("New array")
print(d)

```
```%Run Numpy008.py
Original A
[[1 2 3]
[4 5 6]]
New A
[[1 2]
[3 4]
[5 6]]
New array
[[1 2]
[3 4]
[5 6]]```

How to create an empty array?

```#Creating an empty array
import numpy as np

a = np.empty([3, 2], dtype = int)
print (a)

b = np.empty([3, 2], dtype = float)
print (b)

c = np.empty([3, 2]) #dtype is missing
print ("C is ", c)
```

The above program does not create an ’empty’ array. There are some random values in this array and these are called junk values. We will see how the array can be created with all elements as 0 or all elements as 1.

Create an Array of All Ones or All Zeros

```#Create an array of 0s and 1s
import numpy as np

a = np.zeros(5)
print("a: ", a)

#But if you want an array of int zeros:
b = np.zeros(5, dtype = int)
print("b: ", b)

c = np.zeros((2,2), dtype = int)
print("c: ", c)

#Create array all elements as 1
d = np.ones(5, dtype = int)
print("d: ", d)

```
```%Run Numpy011.py
a: [0. 0. 0. 0. 0.]
b: [0 0 0 0 0]
c: [[0 0]
[0 0]]
d: [1 1 1 1 1]```

To Test if any of the elements of a given array are zero

```#How to test if any elements of an array are 0
import numpy as np

a = np.array([1, 0, 0, 0])
print ("Original array:")
print (a)

print("Test if any of the elements of a given array is non-zero:")
print(np.any(a))

b = np.array([0, 0, 0, 0])
print("Original array:")
print(b)

print("Test if any of the elements of a given array is non-zero:")
print(np.any(b))

```
```%Run Numpy015.py
Original array:
[1 0 0 0]
Test if any of the elements of a given array is non-zero:
True
Original array:
[0 0 0 0]
Test if any of the elements of a given array is non-zero:
False```

To Test if two arrays are equal

```#To test if two arrays are equal
import numpy as np

a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = np.array([1, 2, 4])

print(np.equal(a, b))
print(np.equal(a, c))

```
```%Run Numpy016.py
[ True True True]
[ True True False]```

To create an array of integers whose values lie between p and q

```#WAP to create an array of integers from 10 to 50, both inclusive
import numpy as np

a = np.arange(10, 51, dtype = int)
print(a)

#Modify above to produce only even integers from 10 to 50
b = np.arange(10, 51, 2, dtype = int)
print("Even numbers are : ")
print(b)

```
```%Run Numpy018.py
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50]
Even numbers are :
[10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50]```

Create a 3 x 3 Identity matrix

```#Create a 3x3 identity matrix
import numpy as np

a = np.identity(3, dtype=int)
print(a)

```
```%Run Numpy019.py
[[1 0 0]
[0 1 0]
[0 0 1]]```

How To check the dimensions of an Array?

```import numpy as np
arr1 = np.array(11)
arr2 = np.array([100, 200, 300, 400])
arr3 = np.array([[6, 8, 3], [5, 2, 1]])
arr4 = np.array([[[1, 5, 3], [6, 8, 0]], [[0, 4, 7], [8, 1, 7]]])
print("Dimension: ", arr1.ndim)
print("Dimension: ", arr2.ndim)
print("Dimension: ", arr3.ndim)
print("Dimension: ", arr4.ndim)
```
```Dimension:  0
Dimension:  1
Dimension:  2
Dimension:  3```

How To change the data type of an Array?

```import numpy as np
arr1 = np.array([1, 2, 4, 8, 16, 32])
floatArr1 = arr1.astype('f')
print(floatArr1)
```
`[ 1.  2.  4.  8. 16. 32.]`