Answer 02
NumPy:
NumPy is a python library used for working with arrays. NumPy stands for Numerical Python. It
also has functions for working in domain of linear algebra, Fourier transform, and matrices. It
was created in 2005 by Travis. It is an open source project.
NumPy uses:
Python NumPy arrays provide tools for integrating C, C++, etc. It is also useful in linear algebra,
random number capability etc. NumPy array can also be used as an efficient multi-dimensional
container for generic data.
Python NumPy Array:
Numpy array is a powerful N-dimensional array object which is in the form of rows and
columns. We can initialize NumPy arrays from nested Python lists and access it elements. In
order to perform these NumPy operations, we have to install the numpy.
Installation of NumPy:
To install Python NumPy, go to your command prompt and type “pip install numpy”. Once the
installation is completed, go to your IDE and import it.
Example:
import numpy
arr = numpy.arr([1,2,3,4])
print(arr)
Output:
[1,2,3,4]
Checking NumPy Version:
Example:
Import numpy as np
print(np.__version__)
Output:
1.15.9
Create a NumPy ndarray Object:
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
Example:
Import numpy as np
arr = np.arr([1,2,3,4])
print(arr)
print(type(arr))
Output:
[1,2,3,4]
Class ‘numpy.ndarray’
Dimensions in Arrays:
0-D Array:
Import numpy as np
arr = np.arr(1)
print(arr)
Output:
42
1-D Array:
Import numpy as np
arr = np.arr([1,2,3])
print(arr)
Output:
[1,2,3]
2-D Array:
Import numpy as np
arr = np.arr([[1,2], [3,4]])
print(arr)
Output:
[1,2]
[3,4]
3-D Array:
Import numpy as np
arr = np.arr([[[1,2], [3,4],[[1,2],[3,4]] ])
print(arr)
Output:
[[1,2]
[3,4]]
[[1,2]
[3,4]]
Access Array Elements:
To access the first element:
Import numpy as np
arr = np.arr([1,2,3])
print(arr(0))
Output:
1
To access the second element:
Import numpy as np
arr = np.arr([1,2,3])
print(arr(1))
Output:
2
To access the third element:
Import numpy as np
arr = np.arr([1,2,3])
print(arr(2))
Output:
3
Slicing arrays:
In python, Slicing means taking elements from one given index to another given index.
Example:
Import numpy as np
arr = np.arr([1,2,3,4,5,6,7,8,9])
print(arr(1:6))
Output:
[2,3,4,5,6]
Data Types in NumPy:
NumPy has some extra data types, and refer to data types with one character, like i for integers,
u for unsigned integers etc.