0% found this document useful (0 votes)
9 views

NumPy

NumPy is a Python library designed for efficient array manipulation and numerical computations, created in 2005 by Travis Oliphant. It offers a fast alternative to Python lists with its ndarray object and supports various mathematical functions, including linear algebra and Fourier transforms. Key features include array creation, indexing, slicing, data types, and array operations such as joining, splitting, searching, sorting, and filtering.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

NumPy

NumPy is a Python library designed for efficient array manipulation and numerical computations, created in 2005 by Travis Oliphant. It offers a fast alternative to Python lists with its ndarray object and supports various mathematical functions, including linear algebra and Fourier transforms. Key features include array creation, indexing, slicing, data types, and array operations such as joining, splitting, searching, sorting, and filtering.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

NumPy

NumPy is a Python library.


NumPy is used for working with arrays.
NumPy is short for "Numerical Python".

NumPy Introduction
 NumPy is a Python library used for working with arrays.
 It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
 NumPy was created in 2005 by Travis Oliphant. It is an open source project and you
can use it freely.
 NumPy stands for Numerical Python.

Why Use NumPy?


 In Python we have lists that serve the purpose of arrays, but they are slow to
process.
 NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
 The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.
 Arrays are very frequently used in data science, where speed and resources are very
important.

Why is NumPy Faster Than Lists?


 NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
 This behaviour is called locality of reference in computer science.
 This is the main reason why NumPy is faster than lists. Also, it is optimized to work
with latest CPU architectures.

Which Language is NumPy wri en in?


NumPy is a Python library and is written partially in Python, but most of the parts
that require fast computation are written in C or C++.

Installa on of NumPy
pip install numpy
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)

NumPy as np

NumPy is usually imported under the np alias.

Checking NumPy Version

import numpy as np
print(np.__version__)

NumPy Crea ng Arrays

NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() func on.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

Use a tuple to create a NumPy array:

import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)

Mul Dimensional Array


0-D Arrays
arr = np.array(42)

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

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

Check Number of Dimensions?


print(a.ndim)

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.

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


print(arr[0])

Access 2-D Arrays


arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])

Nega ve Indexing
Use negative indexing to access an array from the end.

NumPy Array Slicing


 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

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


print(arr[1:5])

Nega ve Slicing

Use the minus operator to refer to an index from the end:

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


print(arr[-3:-1])
STEP
Use the step value to determine the step of the slicing:

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


print(arr[1:5:2])

NumPy Data Types

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

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 - medelta
 M - date me
 O - object
 S - string
 U - unicode string
 V - fixed chunk of memory for other type ( void )

Checking the Data Type of an Array

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


print(arr.dtype)
NumPy Array Copy vs View
 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.
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
--------------------------------------------------------------------------------------------------------------------------
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)

NumPy Array Shape

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

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


print(arr.shape)

NumPy Array Reshaping

 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.

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


newarr = arr.reshape(4, 3)
print(newarr)
NumPy Array Itera ng

 Itera ng means going through elements one by one.

 As we deal with mul -dimensional arrays in numpy, we can do this using basic for
loop of python.

 If we iterate on a 1-D array it will go through each element one by one.

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


for x in arr:
print(x)

NumPy Joining Array

 Joining means pu ng contents of two or more arrays in a single array.

 In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.

 We pass a sequence of arrays that we want to join to the concatenate() func on,
along with the axis. If axis is not explicitly passed, it is taken as 0.

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


arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)

NumPy Spli ng Array

 Spli ng is reverse opera on of Joining.

 Joining merges mul ple arrays into one and Spli ng breaks one array into mul ple.

 We use array_split() for spli ng arrays, we pass it the array we want to split and the
number of splits.

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


newarr = np.array_split(arr, 3)
print(newarr)
NumPy 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.

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


x = np.where(arr == 4)
print(x)

NumPy Sor ng Arrays

 Sor ng means pu ng elements in an ordered sequence.

 Ordered sequence is any sequence that has an order corresponding to elements, like
numeric or alphabe cal, ascending or descending.

 The NumPy ndarray object has a func on called sort(), that will sort a specified array.

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


print(np.sort(arr))

NumPy Filter Array

 Ge ng some elements out of an exis ng array and crea ng a new array out of them
is called filtering.
 In NumPy, you filter an array using a boolean index list.

 A boolean index list is a list of booleans corresponding to indexes in the array.

arr = np.array([41, 42, 43, 44])


x = [True, False, True, False]
newarr = arr[x]
print(newarr)

The example above will return [41, 43], why?


Because the new array contains only the values where the filter array had the value True, in
this case, index 0 and 2.
Crea ng the Filter Array

In the example above we hard-coded the True and False values, but the common use is to
create a filter array based on condi ons.

arr = np.array([41, 42, 43, 44])

# Create an empty list


filter_arr = []

# go through each element in arr


for element in arr:
# if the element is higher than 42, set the value to True, otherwise False:
if element > 42:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]
print(filter_arr)
print(newarr)

You might also like