
In NumPy, the key is its array object class, which is quite similar to Python lists. However, arrays have a special rule: every element inside an array must be of the same type, like a number (float or integer). This unique rule allows arrays to work really fast with a lot of numbers, making them much quicker than lists for dealing with big sets of data.
The first step is always to import the NumPy library.
1 >>> import numpy as np
When using NumPy in Python, a common practice is to import it using the shorthand alias np
. This convention is widely adopted and helps save a bit of typing when referring to NumPy functions and objects.
You can support me on Kofi.
How to Create a NumPy array?
2 >>> a = np.array([1,2,3,4,5]) #passing a list in array function to create 1d array
3 >>> a
4 array([1, 2, 3, 4, 5])
5 >>> type(a)
6 numpy.ndarray
In line 2, we use an array() function to create a NumPy array. We pass a list of numbers in the array function to create a 1D array. In line 3, we print the array and in line 5, we check the type of the array and we see that the array is numpy.ndarray. This is a 1-D array.
You can also use a tuple to create an array.
7 >>> a = np.array((1,2,3,4,5))
You can also create the arrays of different dimensions as follows:
8 >>> a = np.array(1) # 0 dim
9 >>> b = np.array([1, 2, 3, 4, 5]) # 1d Array
10 >>> c = np.array([[1, 2, 3], [4, 5, 6]]) #2d array
11 >>> d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) #3d array
12 >>> e = np.array([1, 2, 3, 4, 5], nddim=5)13 >>> print(a)
1
14 >>> print(b)
[1 2 3 4 5]
15 >>> print(c)
[[1 2 3]
[4 5 6]]
16 >>> print(d)
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
17 >>> print(e)
[[[[[1 2 3 4 5]]]]]
You can also make an array of complex numbers.
18 >>> a = np.array([1, 2, 3], dtype=complex)
19 >>> a
array([ 1.+0.j, 2.+0.j…