What is Numpy?
- NumPy is an open-source Python library that’s used in almost every field of science and engineering.
- It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems.
- NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development.
- The NumPy API is used extensively in Pandas, SciPy, Matplotlib, sci-kit-learn, sci-kit-image, and most other data science and scientific Python packages.
- The NumPy library contains multidimensional array and matrix data structures that can be used to perform a wide variety of mathematical operations on arrays.
- It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.
Why not Python Lists?
- NumPy arrays are faster and more compact than Python lists.
- An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.
What is an Array?
An array is a central data structure of the NumPy library. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element. It has a grid of elements that can be indexed in various ways. The elements are all of the same types, referred to as the array dtype.
You need python installed to run NumPy.
The installation will be of the least concern after running the pip install command.
pip install numpy
To make Package or library accessible in your code, you need to import it.
In-case of NumPy, we import numpy here as np.
import numpy as np
The Basics: Creating, Types, Dimensions
One dimension array~ a = np.array([1,2,3])
Two dimension array~ b = np.array([[9.0,8.0,7.0],[6.0,5.0,4.0]])
>>>[[9. 8. 7.]
[6. 5. 4.]]
Array filled with Zeroes~ np.zeros(2)
Array filled with ones~ np.ones(2)
Array filled with Random numbers(not zero)~ np.empty(2)
Array filled with a given range of elements ~ np.arrange(4)
Get Dimension~ a.ndim
>>>1 ##cause a is only of 1 dimension
Get Shape~ b.shape
>>>(2,3) ##cause b is 2by3 matrix
Get Size~ a.itemsize
Get Total Size~ a.nbytes
>>>12 ##total bytes=itemsize*size
Get Number of Elements~ a.size
>>>3 ##elements in the array
Specifying your data type:
- Float~ dtype=np.floatxx
- Integer~ dtype=np.intxx
x = np.ones(2, dtype=np.int64)
>>>array([1, 1]) ##int value
y = np.ones(2, dtype=np.float64)
>>>array([1., 1.]) ##float value