NumPy
NumPy
NumPy Introduction
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you
can use it freely.
NumPy stands for Numerical Python.
Installa on of NumPy
pip install numpy
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy as np
import numpy as np
print(np.__version__)
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() func on.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
1-D Arrays
arr = np.array([1, 2, 3, 4, 5])
2-D Arrays
arr = np.array([[1, 2, 3], [4, 5, 6]])
3-D arrays
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
Nega ve Indexing
Use negative indexing to access an array from the end.
Nega ve Slicing
strings - used to represent text data, the text is given under quote marks. e.g. "ABCD"
integer - used to represent integer numbers. e.g. -1, -2, -3
float - used to represent real numbers. e.g. 1.2, 42.42
boolean - used to represent True or False.
complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 + 2.5j
NumPy has some extra data types, and refer to data types with one character, like i for
integers, u for unsigned integers etc.
Below is a list of all data types in NumPy and the characters used to represent them.
i - integer
b - boolean
u - unsigned integer
f - float
c - complex float
m - medelta
M - date me
O - object
S - string
U - unicode string
V - fixed chunk of memory for other type ( void )
As we deal with mul -dimensional arrays in numpy, we can do this using basic for
loop of python.
In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.
We pass a sequence of arrays that we want to join to the concatenate() func on,
along with the axis. If axis is not explicitly passed, it is taken as 0.
Joining merges mul ple arrays into one and Spli ng breaks one array into mul ple.
We use array_split() for spli ng arrays, we pass it the array we want to split and the
number of splits.
You can search an array for a certain value, and return the indexes that get a match.
To search an array, use the where() method.
Ordered sequence is any sequence that has an order corresponding to elements, like
numeric or alphabe cal, ascending or descending.
The NumPy ndarray object has a func on called sort(), that will sort a specified array.
Ge ng some elements out of an exis ng array and crea ng a new array out of them
is called filtering.
In NumPy, you filter an array using a boolean index list.
In the example above we hard-coded the True and False values, but the common use is to
create a filter array based on condi ons.
newarr = arr[filter_arr]
print(filter_arr)
print(newarr)