Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

NumPy Tutorial

Uploaded by

tsonker182
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

NumPy Tutorial

Uploaded by

tsonker182
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

mport NumPy

Once NumPy is installed, import it in your applications by adding


the import keyword:

import numpy

Now NumPy is imported and ready to use.

Example
import numpy

arr = numpy.array([1, 2, 3, 4, 5])

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.

Create an alias with the as keyword while importing:

import numpy as np

Now the NumPy package can be referred to as np instead of numpy.

Example
import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

Try it Yourself »
Checking NumPy Version
The version string is stored under __version__ attribute.

Example
import numpy as np

print(np.__version__)

NumPy Array Indexing


❮ PreviousNext ❯

Access Array Elements


Array indexing is the same as accessing an array element.

You can access an array element by referring to its index number.

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

arr = np.array([1, 2, 3, 4])

print(arr[0])

Try it Yourself »

Example
Get the second element from the following array.
import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[1])

Try it Yourself »

Example
Get third and fourth elements from the following array and add them.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[2] + arr[3])

Try it Yourself »

ADVERTISEMENT

Access 2-D Arrays


To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.

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

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr[0, 1])

Try it Yourself »

Example
Access the element on the 2nd row, 5th column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('5th element on 2nd row: ', arr[1, 4])

Try it Yourself »

Access 3-D Arrays


To access elements from 3-D arrays we can use comma separated integers
representing the dimensions and the index of the element.

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.

And this is why:

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

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

NumPy Array Slicing


❮ PreviousNext ❯

Slicing arrays
Slicing in python means taking elements from one given index to another
given index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step].


If we don't pass start its considered 0

If we don't pass end its considered length of array in that dimension

If we don't pass step its considered 1

Example
Slice elements from index 1 to index 5 from the following array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])

Try it Yourself »

Example
Slice elements from the beginning to index 4 (not included):

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5:2])

Try it Yourself »

Example
Return every other element from the entire array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

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

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:4])

Try it Yourself »

Note: Remember that second element has index 1.

Example
From both elements, return index 2:

import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

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

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[0:2, 1:4])

NumPy Data Types


❮ PreviousNext ❯
Data Types in Python
By default Python have these data types:

• 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

Data Types in NumPy


NumPy has some extra data types, and refer to data types with one
character, like i for integers, u for unsigned integers etc.

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 )

Checking the Data Type of an Array


The NumPy array object has a property called dtype that returns the data
type of the array:
Example
Get the data type of an array object:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr.dtype)

Try it Yourself »

Example
Get the data type of an array containing strings:

import numpy as np

arr = np.array(['apple', 'banana', 'cherry'])

print(arr.dtype)

Try it Yourself »

ADVERTISEMENT

Creating Arrays With a Defined Data Type


We use the array() function to create arrays, this function can take an
optional argument: dtype that allows us to define the expected data type of
the array elements:

Example
Create an array with data type string:

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='S')

print(arr)
print(arr.dtype)
Try it Yourself »

For i, u, f, S and U we can define size as well.

Example
Create an array with data type 4 bytes integer:

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='i4')

print(arr)
print(arr.dtype)

Try it Yourself »

What if a Value Can Not Be Converted?


If a type is given in which elements can't be casted then NumPy will raise a
ValueError.

ValueError: In Python ValueError is raised when the type of passed


argument to a function is unexpected/incorrect.

Example
A non integer string like 'a' can not be converted to integer (will raise an
error):

import numpy as np

arr = np.array(['a', '2', '3'], dtype='i')

Try it Yourself »

Converting Data Type on Existing Arrays


The best way to change the data type of an existing array, is to make a copy
of the array with the astype() method.
The astype() function creates a copy of the array, and allows you to specify
the data type as a parameter.

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

arr = np.array([1.1, 2.1, 3.1])

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

arr = np.array([1.1, 2.1, 3.1])

newarr = arr.astype(int)

print(newarr)
print(newarr.dtype)

Try it Yourself »

Example
Change data type from integer to boolean:

import numpy as np

arr = np.array([1, 0, 3])

newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)

NumPy Array Copy vs View


❮ PreviousNext ❯

The Difference Between Copy and View


The main difference between a copy and a view of an array is that the copy
is a new array, and the view is just a view of the original array.

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

arr = np.array([1, 2, 3, 4, 5])


x = arr.copy()
arr[0] = 42

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

arr = np.array([1, 2, 3, 4, 5])


x = arr.view()
arr[0] = 42

print(arr)
print(x)

Try it Yourself »

The view SHOULD be affected by the changes made to the original array.

Make Changes in the VIEW:


Example
Make a view, change the view, and display both arrays:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


x = arr.view()
x[0] = 31

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.

Otherwise, the base attribute refers to the original object.

Example
Print the value of the base attribute to check if an array owns it's data or
not:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

x = arr.copy()
y = arr.view()

print(x.base)
print(y.base)

NumPy Array Shape


❮ PreviousNext ❯

Shape of an Array
The shape of an array is the number of elements in each dimension.

Get the Shape of an Array


NumPy arrays have an attribute called shape that returns a tuple with each
index having the number of corresponding elements.
Example
Print the shape of a 2-D array:

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

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

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('shape of array :', arr.shape)

NumPy Array Reshaping


❮ PreviousNext ❯

Reshaping arrays
Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of


elements in each dimension.
Reshape From 1-D to 2-D
Example
Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3) # (4- Rows, 3- Coloumns)

print(newarr)

Try it Yourself »

Reshape From 1-D to 3-D


Example
Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with
2 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

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.

We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array


but we cannot reshape it into a 3 elements 3 rows 2D array as that would
require 3x3 = 9 elements.

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

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(3, 3)

print(newarr)

Try it Yourself »

Returns Copy or View?


Example
Check if the returned array is a copy or a view:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

print(arr.reshape(2, 4).base)

Try it Yourself »

The example above returns the original array, so it is a view.

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

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(2, 2, -1)

print(newarr)

Try it Yourself »

Note: We can not pass -1 to more than one dimension.

Flattening the arrays


Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

Example
Convert the array into a 1D array:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

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.

To search an array, use the where() method.

Example
Find the indexes where the value is 4:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 4, 4])

x = np.where(arr == 4)

print(x)

Try it Yourself »

The example above will return a tuple: (array([3, 5, 6],)

Which means that the value 4 is present at index 3, 5, and 6.

Example
Find the indexes where the values are even:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

x = np.where(arr%2 == 0)

print(x)

Try it Yourself »
Example
Find the indexes where the values are odd:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

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.

The searchsorted() method is assumed to be used on sorted arrays.

Example
Find the indexes where the value 7 should be inserted:

import numpy as np

arr = np.array([6, 7, 8, 9])

x = np.searchsorted(arr, 7)

print(x)

Try it Yourself »

Example explained: The number 7 should be inserted on index 1 to remain


the sort order.

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

arr = np.array([6, 7, 8, 9])

x = np.searchsorted(arr, 7, side='right')

print(x)

Try it Yourself »

Example explained: The number 7 should be inserted on index 2 to remain


the sort order.

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

values 2, 4, and 6 should be inserted:

import numpy as np

arr = np.array([1, 3, 5, 7])

x = np.searchsorted(arr, [2, 4, 6])

print(x)

You might also like