NumPy Stands for numerical python
How do I install NumPy?
To install Python NumPy, go to your command prompt and type “pip install numpy”.
Once the installation is completed, go to your IDE (For example: PyCharm) and simply import it by typing:
“import numpy as np”
Here, I have different elements that are stored in their respective memory locations. It is said to be two dimensional because it has rows as well as columns. In the above image, we have 3 columns and 4 rows available.
How do I start NumPy?
Single-dimensional Numpy Array:
1 2 3 | import numpy as np a = np.array([ 1 , 2 , 3 ]) print (a) |
Output – [1 2 3]
Multi-dimensional Array:
1 2 | a = np.array([( 1 , 2 , 3 ),( 4 , 5 , 6 )]) print (a) |
O/P – [[ 1 2 3]
[4 5 6]]
Python NumPy Array v/s List
Why NumPy is used in Python?
We use python NumPy array instead of a list because of the below three reasons:
- Less Memory
- Fast
- Convenient
The very first reason to choose python NumPy array is that it occupies less memory as compared to list.
Then, it is pretty fast in terms of execution and at the same time, it is very convenient to work with NumPy.
Python NumPy Operations:
ndim:
You can find the dimension of the array, whether it is a two-dimensional array or a single dimensional array. So, let us see this practically how we can find the dimensions. In the below code, with the help of ‘ndim’ function, I can find whether the array is of single dimension or multi dimension.
1 2 3 | import numpy as np a = np.array([( 1 , 2 , 3 ),( 4 , 5 , 6 )]) print (a.ndim) |
Output – 2
Since the output is 2, it is a two-dimensional array (multi dimension).
itemsize:
You can calculate the byte size of each element. In the below code, I have defined a single dimensional array and with the help of ‘itemsize’ function, we can find the size of each element.
1 2 3 | import numpy as np a = np.array([( 1 , 2 , 3 )]) print (a.itemsize) |
Output – 4
So every element occupies 4 byte in the above numpy array.
dtype:
You can find the data type of the elements that are stored in an array. So, if you want to know the data type of a particular element, you can use ‘dtype’ function which will print the datatype along with the size. In the below code, I have defined an array where I have used the same function.
1 2 3 | import numpy as np a = np.array([( 1 , 2 , 3 )]) print (a.dtype) |
Output – int32
1 2 3 4 | import numpy as np a = np.array([( 1 , 2 , 3 , 4 , 5 , 6 )]) print (a.size) print (a.shape) |
Output – 6 (1,6)
reshape:
Reshape is when you change the number of rows and columns which gives a new view to an object. Now, let us take an example to reshape the below array:As you can see in the above image, we have 3 columns and 2 rows which has converted into 2 columns and 3 rows. Let me show you practically how it’s done.
12345import
numpy as np
a
=
np.array([(
8
,
9
,
10
),(
11
,
12
,
13
)])
print
(a)
a
=
a.reshape(
3
,
2
)
print
(a)
Output – [[ 8 9 10] [11 12 13]] [[ 8 9] [10 11] [12 13]]
slicing:
Before getting into the above example, let’s see a simple one. We have an array and we need a particular element (say 3) out of a given array. Let’s consider the below example:
123import
numpy as np
a
=
np.array([(
1
,
2
,
3
,
4
),(
3
,
4
,
5
,
6
)])
print
(a[
0
,
2
])
Output – 3
Here, the array(1,2,3,4) is your index 0 and (3,4,5,6) is index 1 of the python numpy array. Therefore, we have printed the second element from the zeroth index.
Taking one step forward, let’s say we need the 2nd element from the zeroth and first index of the array. Let’s see how you can perform this operation:123import
numpy as np
a
=
np.array([(
1
,
2
,
3
,
4
),(
3
,
4
,
5
,
6
)])
print
(a[
0
:,
2
])
Output – [3 5]
Here colon represents all the rows, including zero. Now to get the 2nd element, we’ll call index 2 from both of the rows which gives us the value 3 and 5 respectively.
Next, just to remove the confusion, let’s say we have one more row and we don’t want to get its 2nd element printed just as the image above. What we can do in such case?
Consider the below code:123import
numpy as np
a
=
np.array([(
8
,
9
),(
10
,
11
),(
12
,
13
)])
print
(a[
0
:
2
,
1
])
Output – [9 11]
As you can see in the above code, only 9 and 11 gets printed. Now when I have written 0:2, this does not include the second index of the third row of an array. Therefore, only 9 and 11 gets printed else you will get all the elements i.e [9 11 13].
This function returns a copy of an array collapsed into one dimension. The function takes the following parameters.
ndarray.flatten(order)
import numpy as np a = np.arange(8).reshape(2,4) print 'The original array is:' print a print '\n' # default is column-major print 'The flattened array is:' print a.flatten() print '\n' print 'The flattened array in F-style ordering:' print a.flatten(order = 'F')
The output of the above program would be as follows −
The original array is: [[0 1 2 3] [4 5 6 7]] The flattened array is: [0 1 2 3 4 5 6 7] The flattened array in F-style ordering: [0 4 1 5 2 6 3 7]
NumPy – Broadcasting
The term broadcasting refers to the ability of NumPy to treat arrays of different shapes during arithmetic operations. Arithmetic operations on arrays are usually done on corresponding elements. If two arrays are of exactly the same shape, then these operations are smoothly performed.
Example 1
import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])
c = a * b
print c
Its output is as follows −[10 40 90 160]
If the dimensions of the two arrays are dissimilar, element-to-element operations are not possible. However, operations on arrays of non-similar shapes is still possible in NumPy, because of the broadcasting capability. The smaller array is broadcast to the size of the larger array so that they have compatible shapes.
Broadcasting is possible if the following rules are satisfied −
- Array with smaller ndim than the other is prepended with ‘1’ in its shape.
- Size in each dimension of the output shape is maximum of the input sizes in that dimension.
- An input can be used in calculation if its size in a particular dimension matches the output size or its value is exactly 1.
- If an input has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.
A set of arrays is said to be broadcastable if the above rules produce a valid result and one of the following is true −
- Arrays have exactly the same shape.
- Arrays have the same number of dimensions and the length of each dimension is either a common length or 1.
- Array having too few dimensions can have its shape prepended with a dimension of length 1, so that the above stated property is true.
The following figure demonstrates how array b is broadcast to become compatible with a.
Comments
Post a Comment