Wait, the name is crazy. NumPy is numbers + Python !?
You are almost right! It is first half of Numerical and first half of Python. NumPy = Numerical + Python.
Okay. Got to know the full form first.
So, what is this?
NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
— Ctrl V from Google 😌
So, why to learn NumPy?
It is like at least 10–100 times faster than native Python data structure like list. It is just like a race between a cyclist & a Lamborghini.
Here is a short & cute example.
python_list = list(range(100000))
numpy_array = np.arange(100000)
%timeit numpy_array * 2
%timeit [i*2 for i in python_list]
Output is
32.3 µs ± 57.3 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
2.38 ms ± 6.95 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.38 ms is 2380 µs. NumPy is ~100X faster. Wow, that’s great. Now, I am motivated to learn this awesome tool.
Now, tell me how to create a NumPy array?
There are many ways to create NumPy arrays. Let’s see them one-by-one.
But wait, first you should import numpy before using it.
Tip: The most famous convention is import numpy as np.
Ways to create NumPy arrays.
- arange: Not orange! It is the same as range function in Python. It creates an array from 0 to N (excluded)
np.arange(10) #array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2. If you want to covert List to ndarray, use np.array(). (numpy.ndarray is the type of all NumPy arrays).
np.array([3,4,5]) #array([3, 4, 5])
3. Want to create random numbers? Then, use np.random.randn() (there are many ways possible too)
np.random.randn(2,3) #array([[-0.3226426 , -1.45057072, 0.83590113],
[-0.51700647, -1.13528089, -0.30493445]])
Tip: Use np.random? to see all functions available.
- np.ndarray — Directly input the shape to it & it generates a random numpy array.
np.ndarray([2,3]) #array([[0.00000e+000, 4.94066e-324, 9.88131e-324],
[4.94051e-319, 4.94056e-319, 4.94061e-319]])
5. Want to give custom values? Then, use np.fill().
numpyArray.fill(3) #array([[3., 3., 3.],
[3., 3., 3.]])
6. ones(), zeros(), empty() — Used to fill 1s, 0s and random values respectively.
Well, that’s about creating NumPy arrays, in the next blog let’s see about ________
If you have liked the content, please hit the “Clap” button and,
Connect with me -
*LinkedIn :* [*https://linkedin.com/in/bomma-pranay*](https://linkedin.com/in/bomma-pranay)*GitHub :* [*https://github.com/Bomma-Pranay*](https://github.com/Bomma-Pranay)
*--- By Pranay Bomma A Data Science Enthusiast*