NumPy Tutorial
NumPy Tutorial
import numpy
Example
import numpy
print(arr)
Try it Yourself »
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same thing.
import numpy as np
Example
import numpy as np
print(arr)
Try it Yourself »
Checking NumPy Version
The version string is stored under __version__ attribute.
Example
import numpy as np
print(np.__version__)
The indexes in NumPy arrays start with 0, meaning that the first element has
index 0, and the second has index 1 etc.
Example
Get the first element from the following array:
import numpy as np
print(arr[0])
Try it Yourself »
Example
Get the second element from the following array.
import numpy as np
print(arr[1])
Try it Yourself »
Example
Get third and fourth elements from the following array and add them.
import numpy as np
print(arr[2] + arr[3])
Try it Yourself »
ADVERTISEMENT
Think of 2-D arrays like a table with rows and columns, where the row
represents the dimension and the index represents the column.
Example
Access the element on the first row, second column:
import numpy as np
Try it Yourself »
Example
Access the element on the 2nd row, 5th column:
import numpy as np
Try it Yourself »
Example
Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Try it Yourself »
Example Explained
arr[0, 1, 2] prints the value 6.
The first number represents the first dimension, which contains two arrays:
[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]
Since we selected 0, we are left with the first array:
[[1, 2, 3], [4, 5, 6]]
The second number represents the second dimension, which also contains
two arrays:
[1, 2, 3]
and:
[4, 5, 6]
Since we selected 1, we are left with the second array:
[4, 5, 6]
The third number represents the third dimension, which contains three
values:
4
5
6
Since we selected 2, we end up with the third value:
6
Negative Indexing
Use negative indexing to access an array from the end.
Example
Print the last element from the 2nd dim:
import numpy as np
Slicing arrays
Slicing in python means taking elements from one given index to another
given index.
Example
Slice elements from index 1 to index 5 from the following array:
import numpy as np
print(arr[1:5])
Try it Yourself »
Note: The result includes the start index, but excludes the end index.
Example
Slice elements from index 4 to the end of the array:
import numpy as np
print(arr[4:])
Try it Yourself »
Example
Slice elements from the beginning to index 4 (not included):
import numpy as np
print(arr[:4])
Try it Yourself »
ADVERTISEMENT
Negative Slicing
Use the minus operator to refer to an index from the end:
Example
Slice from the index 3 from the end to index 1 from the end:
import numpy as np
print(arr[-3:-1])
Try it Yourself »
STEP
Use the step value to determine the step of the slicing:
Example
Return every other element from index 1 to index 5:
import numpy as np
print(arr[1:5:2])
Try it Yourself »
Example
Return every other element from the entire array:
import numpy as np
print(arr[::2])
Try it Yourself »
Slicing 2-D Arrays
Example
From the second element, slice elements from index 1 to index 4 (not
included):
import numpy as np
print(arr[1, 1:4])
Try it Yourself »
Example
From both elements, return index 2:
import numpy as np
print(arr[0:2, 2])
Try it Yourself »
Example
From both elements, slice index 1 to index 4 (not included), this will return a
2-D array:
import numpy as np
print(arr[0:2, 1:4])
• 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
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 - timedelta
• M - datetime
• O - object
• S - string
• U - unicode string
• V - fixed chunk of memory for other type ( void )
import numpy as np
print(arr.dtype)
Try it Yourself »
Example
Get the data type of an array containing strings:
import numpy as np
print(arr.dtype)
Try it Yourself »
ADVERTISEMENT
Example
Create an array with data type string:
import numpy as np
print(arr)
print(arr.dtype)
Try it Yourself »
Example
Create an array with data type 4 bytes integer:
import numpy as np
print(arr)
print(arr.dtype)
Try it Yourself »
Example
A non integer string like 'a' can not be converted to integer (will raise an
error):
import numpy as np
Try it Yourself »
The data type can be specified using a string, like 'f' for float, 'i' for integer
etc. or you can use the data type directly like float for float and int for
integer.
Example
Change data type from float to integer by using 'i' as parameter value:
import numpy as np
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)
Try it Yourself »
Example
Change data type from float to integer by using int as parameter value:
import numpy as np
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)
Try it Yourself »
Example
Change data type from integer to boolean:
import numpy as np
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)
The copy owns the data and any changes made to the copy will not affect
original array, and any changes made to the original array will not affect the
copy.
The view does not own the data and any changes made to the view will affect
the original array, and any changes made to the original array will affect the
view.
COPY:
Example
Make a copy, change the original array, and display both arrays:
import numpy as np
print(arr)
print(x)
Try it Yourself »
The copy SHOULD NOT be affected by the changes made to the original
array.
VIEW:
Example
Make a view, change the original array, and display both arrays:
import numpy as np
print(arr)
print(x)
Try it Yourself »
The view SHOULD be affected by the changes made to the original array.
import numpy as np
print(arr)
print(x)
Try it Yourself »
The original array SHOULD be affected by the changes made to the view.
ADVERTISEMENT
Check if Array Owns its Data
As mentioned above, copies owns the data, and views does not own the
data, but how can we check this?
Every NumPy array has the attribute base that returns None if the array owns
the data.
Example
Print the value of the base attribute to check if an array owns it's data or
not:
import numpy as np
x = arr.copy()
y = arr.view()
print(x.base)
print(y.base)
Shape of an Array
The shape of an array is the number of elements in each dimension.
import numpy as np
print(arr.shape)
Try it Yourself »
The example above returns (2, 4), which means that the array has 2
dimensions, where the first dimension has 2 elements and the second has 4.
Example
Create an array with 5 dimensions using ndmin using a vector with values
1,2,3,4 and verify that last dimension has value 4:
import numpy as np
print(arr)
print('shape of array :', arr.shape)
Reshaping arrays
Reshaping means changing the shape of an array.
import numpy as np
print(newarr)
Try it Yourself »
The outermost dimension will have 2 arrays that contains 3 arrays, each with
2 elements:
import numpy as np
newarr = arr.reshape(2, 3, 2)
print(newarr)
Try it Yourself »
ADVERTISEMENT
Can We Reshape Into any Shape?
Yes, as long as the elements required for reshaping are equal in both shapes.
Example
Try converting 1D array with 8 elements to a 2D array with 3 elements in
each dimension (will raise an error):
import numpy as np
newarr = arr.reshape(3, 3)
print(newarr)
Try it Yourself »
import numpy as np
print(arr.reshape(2, 4).base)
Try it Yourself »
Unknown Dimension
You are allowed to have one "unknown" dimension.
Meaning that you do not have to specify an exact number for one of the
dimensions in the reshape method.
Pass -1 as the value, and NumPy will calculate this number for you.
Example
Convert 1D array with 8 elements to 3D array with 2x2 elements:
import numpy as np
print(newarr)
Try it Yourself »
Example
Convert the array into a 1D array:
import numpy as np
newarr = arr.reshape(-1)
print(newarr)
NumPy Searching Arrays
❮ PreviousNext ❯
Searching Arrays
You can search an array for a certain value, and return the indexes that get a
match.
Example
Find the indexes where the value is 4:
import numpy as np
x = np.where(arr == 4)
print(x)
Try it Yourself »
Example
Find the indexes where the values are even:
import numpy as np
x = np.where(arr%2 == 0)
print(x)
Try it Yourself »
Example
Find the indexes where the values are odd:
import numpy as np
x = np.where(arr%2 == 1)
print(x)
Try it Yourself »
ADVERTISEMENT
Search Sorted
There is a method called searchsorted() which performs a binary search in the
array, and returns the index where the specified value would be inserted to
maintain the search order.
Example
Find the indexes where the value 7 should be inserted:
import numpy as np
x = np.searchsorted(arr, 7)
print(x)
Try it Yourself »
The method starts the search from the left and returns the first index where
the number 7 is no longer larger than the next value.
Search From the Right Side
By default the left most index is returned, but we can give side='right' to
return the right most index instead.
Example
Find the indexes where the value 7 should be inserted, starting from the
right:
import numpy as np
x = np.searchsorted(arr, 7, side='right')
print(x)
Try it Yourself »
The method starts the search from the right and returns the first index where
the number 7 is no longer less than the next value.
Multiple Values
To search for more than one value, use an array with the specified values.
Example
Find the indexes where the
import numpy as np
print(x)