[Go to site: main page, start]

0% found this document useful (0 votes)
10 views18 pages

NumPy Basics: Arrays and Operations

Notes of Numpy framework

Uploaded by

John Abraham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

NumPy Basics: Arrays and Operations

Notes of Numpy framework

Uploaded by

John Abraham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO NUMPY

What is NumPy?
NumPy is a general-purpose array-processing package. It provides a high-
performance multidimensional array object and tools for working with these
arrays. It is the fundamental package for scientific computing with Python. It is
open-source software.

Array in NUMPY-
NumPy’s main object is the homogeneous multidimensional array.
 It is a table of elements (usually numbers), all of the same type, indexed by
a tuple of positive integers.
 In NumPy, dimensions are called axes. The number of axes is rank.
 NumPy’s array class is called ndarray. It is also known by the alias array.

import numpy as np

# Creating array object


arr = [Link]( [[ 1, 2, 3],
[ 4, 2, 5]] )

# Printing type of arr object


print("Array is of type: ", type(arr))

# Printing array dimensions (axes)


print("No. of dimensions: ", [Link])

# Printing shape of array


print("Shape of array: ", [Link])

# Printing size (total number of elements) of array


print("Size of array: ", [Link])

# Printing type of elements in array


print("Array stores elements of type: ", [Link])

Output:
Array is of type: <class '[Link]'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64

NUMPY Array Creation-

1. Using Array function-

import numpy as np

# Creating array from list with type float


a = [Link]([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

# Creating array from tuple


b = [Link]((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

Output:
Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]

Array created using passed tuple:


[1 3 2]

2. Using [Link], [Link], [Link], [Link], etc.


Array with initial placeholder content.

# Creating a 3X4 array with all zeros


c = [Link]((3, 4))
print ("An array initialized with all zeros:\n", c)

# Create a constant value array of complex type


d = [Link]((3, 3), 6, dtype = 'complex')
print ("An array initialized with all 6s."
"Array type is complex:\n", d)

Output:
An array initialized with all zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized with all [Link] type is complex:
[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]

3. Arange- This function returns evenly spaced values within a given


interval. Step size is defined.

# Create a sequence of integers


# from 0 to 30 with steps of 5
f = [Link](0, 30, 5)
print ("A sequential array with steps of 5:\n", f)

Output:
A sequential array with steps of 5:
[ 0 5 10 15 20 25]

4. Linspace- It returns evenly spaced values within a given interval.

# Create a sequence of 10 values in range 0 to 5


g = [Link](0, 5, 10)
print ("A sequential array with 10 values between"
"0 and 5:\n", g)

Output:
A sequential array with 10 values between0 and 5:
[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]

5. Reshaping array- use reshape method.

# Reshaping 3X4 array to 2X2X3 array


arr = [Link]([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])

newarr = [Link](2, 2, 3)

print ("Original array:\n", arr)


print("---------------")
print ("Reshaped array:\n", newarr)

Output:
Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
---------------
Reshaped array:
[[[1 2 3]
[4 5 2]]
[[4 2 1]
[2 0 1]]]

6. Flatten array- use flatten method

# Flatten array
arr = [Link]([[1, 2, 3], [4, 5, 6]])
flat_arr = [Link]()

print ("Original array:\n", arr)


print ("Fattened array:\n", flat_arr)

Output:
Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]

NUMPY Array Indexing-


1. Slicing- Just like lists in Python, NumPy arrays can be sliced. As
arrays can be multidimensional, you need to specify a slice for each
dimension of the array.
2. Integer array indexing-In this method, lists are passed for indexing
for each dimension. One-to-one mapping of corresponding elements
is done to construct a new arbitrary array.
3. Boolean array indexing-This method is used when we want to pick
elements from the array which satisfy some condition.

import numpy as np

# An exemplar array
arr = [Link]([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])

# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)

# Integer array indexing example


temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1),"
"(3, 0):\n", temp)

# boolean array indexing example


cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)

Output:
Array with first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]

Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):


[ 4. 6. 0. 3.]

Elements greater than 0:


[ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]

Basic NUMPY Operations-

Operations on a single NumPy array


We can use overloaded arithmetic operators to do element-wise operations on
the array to create a new array. In the case of +=, -=, *= operators, the existing
array is modified.

import numpy as np

a = [Link]([1, 2, 5, 3])
# add 1 to every element
print ("Adding 1 to every element:", a+1)

# subtract 3 from each element


print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10


print ("Multiplying each element by 10:", a*10)

# square each element


print ("Squaring each element:", a**2)

# modify existing array


a *= 2
print ("Doubled each element of original array:", a)

# transpose of array
a = [Link]([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

print ("\nOriginal array:\n", a)


print ("Transpose of array:\n", a.T)

OUTPUT:

Adding 1 to every element: [2 3 6 4]


Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]

Original array:
[[1 2 3]
[3 4 5]
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]

NumPy – Unary Operators:


Many unary operations are provided as a method of ndarray class. This
includes sum, min, max, etc. These functions can also be applied row-wise or
column-wise by setting an axis parameter.

import numpy as np

arr = [Link]([[1, 5, 6],


[4, 7, 2],
[3, 1, 9]])

# maximum element of array


print ("Largest element is:", [Link]())
print ("Row-wise maximum elements:",
[Link](axis = 1))

# minimum element of array


print ("Column-wise minimum elements:",
[Link](axis = 0))

# sum of array elements


print ("Sum of all array elements:",
[Link]())

# cumulative sum along each row


print ("Cumulative sum along each row:\n",
[Link](axis = 1))

OUTPUT:

Largest element is: 9


Row-wise maximum elements: [6 7 9]
Column-wise minimum elements: [1 1 2]
Sum of all array elements: 38
Cumulative sum along each row:
[[ 1 6 12]
[ 4 11 13]
[ 3 4 13]]

NumPy – Binary Operators:


These operations apply to the array elementwise and a new array is created.
You can use all basic arithmetic operators like +, -, /, etc. In the case of +=, -
=, = operators, the existing array is modified.

import numpy as np

a = [Link]([[1, 2],
[3, 4]])
b = [Link]([[4, 3],
[2, 1]])

# add arrays
print ("Array sum:\n", a + b)

# multiply arrays (elementwise multiplication)


print ("Array multiplication:\n", a*b)

# matrix multiplication
print ("Matrix multiplication:\n", [Link](b))

OUTPUT:
Array sum:
[[5 5]
[5 5]]
Array multiplication:
[[4 6]
[6 4]]
Matrix multiplication:
[[ 8 5]
[20 13]]

NumPy Sorting Arrays:

import numpy as np

a = [Link]([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])

# sorted array
print ("Array elements in sorted order:\n",
[Link](a, axis = None))

# sort array row-wise


print ("Row-wise sorted array:\n",
[Link](a, axis = 1))

# specify sort algorithm


print ("Column wise sort by applying merge-sort:\n",
[Link](a, axis = 0, kind = 'mergesort'))

# Example to show sorting of structured array


# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

# Values to be put in array


values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]

# Creating array
arr = [Link](values, dtype = dtypes)
print ("\nArray sorted by names:\n",
[Link](arr, order = 'name'))

print ("Array sorted by graduation year and then cgpa:\n",


[Link](arr, order = ['grad_year', 'cgpa']))

OUTPUT:
Array elements in sorted order:
[-1 0 1 2 3 4 4 5 6]
Row-wise sorted array:
[[ 1 2 4]
[ 3 4 6]
[-1 0 5]]
Column wise sort by applying merge-sort:
[[ 0 -1 2]
[ 1 4 5]
[ 3 4 6]]

Array sorted by names:


[('Aakash', 2009, 9.0) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5)
('Pankaj', 2008, 7.9)]
Array sorted by graduation year and then cgpa:
[('Pankaj', 2008, 7.9) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5)
('Aakash', 2009, 9.0)]

NUMPY Array manipulation—copy and view

The main difference between copy and view is that the copy is the new array
whereas the view is the view of the original array. In other words, it can be said
that the copy is physically stored at another location and view has the same
memory location as the original array.
No Copy: Normal assignments do not make the copy of an array object. Instead,
it uses the exact same id of the original array to access it. Further, any changes
in either get reflected in the other.
import numpy as np

# creating array
arr = [Link]([2, 4, 6, 8, 10])

# assigning arr to nc
nc = arr

# both arr and nc have same id


print("id of arr", id(arr))
print("id of nc", id(nc))

# updating nc
nc[0]= 12

# printing the values


print("original array- ", arr)
print("assigned array- ", nc)
Output-
id of arr 26558736
id of nc 26558736
original array- [12 4 6 8 10]
assigned array- [12 4 6 8 10]
View: This is also known as Shallow Copy. The view is just a view of the
original array and view does not own the data. When we make changes to the
view it affects the original array, and when changes are made to the original
array it affects the view.
import numpy as np

# creating array
arr = [Link]([2, 4, 6, 8, 10])

# creating view
v = [Link]()

# both arr and v have different id


print("id of arr", id(arr))
print("id of v", id(v))

# changing original array


# will effect view
arr[0] = 12

# printing array and view


print("original array- ", arr)
print("view- ", v)

Output—
id of arr 30480448
id of v 30677968
original array- [12 4 6 8 10]
view- [12 4 6 8 10]
Copy: This is also known as Deep Copy. The copy is completely a new array
and copy owns the data. When we make changes to the copy it does not affect
the original array, and when changes are made to the original array it does not
affect the copy.

import numpy as np

# creating array
arr = [Link]([2, 4, 6, 8, 10])

# creating copy of array


c = [Link]()

# both arr and c have different id


print("id of arr", id(arr))
print("id of c", id(c))

# changing original array


# this will not effect copy
arr[0] = 12

# printing array and copy


print("original array- ", arr)
print("copy- ", c)

Output--

id of arr 35406048
id of c 32095936
original array- [12 4 6 8 10]
copy- [ 2 4 6 8 10]
Array Owning it’s Data:

To check whether array own it’s data in view and copy we can use the fact that
every NumPy array has the attribute base that returns None if the array owns
the data. Else, the base attribute refers to the original object.
import numpy as np

# creating array
arr = [Link]([2, 4, 6, 8, 10])

# creating copy of array


c = [Link]()

# creating view of array


v = [Link]()

# printing base attribute of copy and view


print([Link])
print([Link])

Output--
None
[ 2 4 6 8 10]
How to access different rows of a multidimensional array?
Case-1: 2-D array
# Importing Numpy module
import numpy as np

# Creating a 3X3 2-D Numpy array


arr = [Link]([[10, 20, 30],
[40, 5, 66],
[70, 88, 94]])

print("Given Array :")


print(arr)

# Access the First and Last rows of array


res_arr = arr[[0,2]]
print("\nAccessed Rows :")
print(res_arr)

Example 2:
# Importing Numpy module
import numpy as np

# Creating a 3X4 2-D Numpy array


arr = [Link]([[101, 20, 3, 10],
[40, 5, 66, 7],
[70, 88, 9, 141]])

print("Given Array :")


print(arr)

# Access the Middle row of array


res_arr = arr[1]
print("\nAccessed Row :")
print(res_arr)

Example 3:
# Importing Numpy module
import numpy as np

# Creating a 4X4 2-D Numpy array


arr = [Link]([[1, 20, 3, 1],
[40, 5, 66, 7],
[70, 88, 9, 11],
[80, 100, 50, 77]])

print("Given Array :")


print(arr)

# Access the Last three rows of array


res_arr = arr[[1,2,3]]
print("\nAccessed Rows :")
print(res_arr)

Example 4:
# Importing Numpy module
import numpy as np

# Creating a 5X4 2-D Numpy array


arr = [Link]([[1, 20, 3, 1],
[40, 5, 66, 7],
[70, 88, 9, 11],
[80, 100, 50, 77],
[1, 8.5, 7.9, 4.8]])

print("Given Array :")


print(arr)

# Access the First two rows of array


res_arr = arr[[0,1]]
print("\nAccessed Rows :")
print(res_arr)

Case 2: 3-D arrays


# Importing Numpy module
import numpy as np

# Creating 3-D Numpy array


n_arr = [Link]([[[10, 25, 70], [30, 45, 55], [20, 45, 7]],
[[50, 65, 8], [70, 85, 10], [11, 22, 33]]])

print("Given 3-D Array:")


print(n_arr)

# Access the Middle rows of 3-D array


res_arr = n_arr[:,[1]]
print("\nAccessed Rows :")
print(res_arr)

Example 2:
# Importing Numpy module
import numpy as np

# Creating 3-D Numpy array


n_arr = [Link]([[[10, 25, 70], [30, 45, 55], [20, 45, 7]],
[[50, 65, 8], [70, 85, 10], [11, 22, 33]],
[[19, 69, 36], [1, 5, 24], [4, 20, 96]]])

print("Given 3-D Array:")


print(n_arr)

# Access the First and Last rows of 3-D array


res_arr = n_arr[:,[0, 2]]
print("\nAccessed Rows :")
print(res_arr)

Example 2:
# 3-dimensional array
array3D = [Link]([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],

[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],

[[18, 19, 20],


[21, 22, 23],
[24, 25, 26]]])

print(array3D)
print("shape :" +str([Link]))

print("\naccessing element :" +str(array3D[0, 1, 0]))


print("accessing elements of a row and a column of an array:"
+str(array3D[:, 1, 0]))
print("accessing sub part of an array :" +str(array3D[1]))

File input outuput with array:


NumPy offers input/output (I/O) functions for loading and saving data to and
from files.
Input/output functions support a variety of file formats, including binary and text
formats.
 The binary format is designed for efficient storage and retrieval of large
arrays.
 The text format is more human-readable and can be easily edited in a text
editor.

Most Commonly Used I/O Functions

Here are some of the commonly used NumPy Input/Output functions:

Function Description

save() saves an array to a binary file in the NumPy .npy format.

load() loads data from a binary file in the NumPy .npy format

savetxt() saves an array to a text file in a specific format

loadtxt() loads data from a text file.

NumPy save() Function


In NumPy, the save() function is used to save an array to a binary file in the
NumPy .npy format.
Here's the syntax of the save() function,
[Link](file, array)
 file - specifies the file name (along with path if required)
 array - specifies the NumPy array to be saved

Example:
import numpy as np
# create a NumPy array
array1 = [Link]([[1, 3, 5],
[7, 9, 11]])
# save the array to a file
[Link]('[Link]', array1)
# load the saved NumPy array
loaded_array = [Link]('[Link]')

# display the loaded array


print(loaded_array)

NumPy savetxt() Function


In NumPy, we use the savetxt() function to save an array to a text file.
Here's the syntax of the savetxt() function:
[Link](file, array)
 file - specifies the file name
 array - specifies the NumPy array to be saved

Example:
import numpy as np
# create a NumPy array
array2 = [Link]([[1, 3, 5],
[7, 9, 11]])
# save the array to a file
[Link]('[Link]', array2)
# load the saved NumPy array
loaded_array = [Link]('[Link]')
# display the loaded array
print(loaded_array)

You might also like