0% found this document useful (0 votes)
2 views33 pages

Array in Python

Uploaded by

Nivedika Namburi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
2 views33 pages

Array in Python

Uploaded by

Nivedika Namburi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 33

ARRAY IN PYTHON

NUMPY LIBRARY
UNIT 4
ARRAY

• In Python, Array is an object that provide a mechanism for storing


several data items with only one identifier, thereby simplifying the task
of data management.
• Array is beneficial if you need to store group of elements of same
datatype.
• In python , Arrays can increase or decrease their size dynamically .
KEY POINTS

• Arrays can store only one type of data.


• In Python , the size of array is not fixed . Array can increase or
decrease their size dynamically but only with the use of numpy library .
• Array and list are not same
• Array uses less memory than list
WHY WE NEED ARRAY???
TYPE OF ARRAY
CREATING ID ARRAY USING ARRAY MODULE
ANOTHER WAY TO CREATING ARRAY
LIMITATION OF USING ARRAY MODULE

• Fixed size
• Array module doesn't support multi dimensions.
• It doesn't support implicit type conversion
NUMPY ARRAY

• NumPy stands for Numerical Python and is used for working with
arrays and matrices. It is faster than Python lists and is written in C or
C++ for efficient computation.
• A NumPy array, also known as ndarray (N-dimensional array), is a
powerful data structure provided by the NumPy library in Python.
• It is designed for efficient numerical computations and is widely used
in scientific computing, data analysis, and machine learning.
IMPORT NUMPY
CREATING NUMPY ARRAY WITH EXAMPLE
CODE
• import numpy as np
• # Create a 1D array
• arr1 = np.array([1, 2, 3, 4, 5])
• # Create a 2D array
• arr2 = np.array([[1, 2, 3], [4, 5, 6]])
• #displaying array elements
• print("1D Array:", arr1)
• print("2D Array:", arr2)
MEMORY ALLOCATED TO NUMPY ARRAYS
DATA TYPES.

• NumPy arrays support a variety of data types.


• Boolean:
bool_: Boolean (True or False) stored as a byte.
• Integers:
int_, int8, int16, int32, int64: Signed integer types with different bit sizes.
uint8, uint16, uint32, uint64: Unsigned integer types with different bit
sizes.
• Floating Point:

float_, float16, float32, float64: Floating point types with different precision levels.
• Complex:

complex_, complex64, complex128: Complex number types with different


precision levels.
• String and Bytes:

str_: Unicode string type.


bytes_: Byte string type.
EXAMPLE

• import numpy as np
# Complex array
• # Integer array complex_array = np.array([1+2j, 3+4j, 5+6j])
• int_array = np.array([1, 2, 3])
print("Integer array:", int_array)
• # Float array print("Float array:", float_array)
print("Boolean array:", bool_array)
• float_array = np.array([1.1, 2.2, 3.3]) print("Complex array:", complex_array)

• # Boolean array
• bool_array = np.array([True, False, True])
INDEXING IN NUMPY ARRAY

• Indexing can be done in numpy by using an array as an index


• In NumPy, each element in an array is associated with a number. The
number is known as an array index.
• Let's see an example to demonstrate NumPy array indexing.

In the above array, 5 is the 3rd element. However, its index is 2.


This is because the array indexing starts from 0, that is, the first element of the
array has index 0, the second element has index 1, and so on.
ACCESS 1D ARRAY ELEMENTS USING
INDEX
• We can use indices to access individual elements of a NumPy array.
• Suppose we have a NumPy array:

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


Now, we can use the index number to access array elements as:

array1[0] - to access the first element, i.e. 1


array1[2] - to access the third element, i.e. 5
array1[4] - to access the fifth element, i.e. 9
EXAMPLE CODE

import numpy as np
array1 = np.array([1, 3, 5, 7, Note: Since the last element of array1 is at index
9]) 4, if we try to access the element beyond that,
say index 5, we will get an index error:
# access numpy elements IndexError: index 5 is out of bounds for axis 0
using index with size 5
print(array1[0]) # prints 1
print(array1[2]) # prints 5
print(array1[4]) # prints 9
ACCESS 2D ARRAY ELEMENTS USING
INDEX
• In NumPy, we can access specific rows or columns of a 2-D array using
array indexing.
• To access an element of array1, we need to specify the row index and
column index of the element. Suppose we have following 2-D array
array1 = np.array([[1, 3, 5], [7, 9, 2],[4, 6, 8]])
• Now, say we want to access the element in the third row and second
column we specify the index as
array1[2, 1] # returns 6
EXAMPLE CODE

• import numpy as np

# create a 2D array
• array1 = np.array([[1, 3, 5, 7],[9, 11, 13, 15],[2, 4, 6, 8]])
• # access the element at the second row and fourth column
• element1 = array1[1, 3] # returns 15
• print("4th Element at 2nd Row:",element1)

# access the element at the first row and second column


• element2 = array1[0, 1] # returns 3
• print("2nd Element at First Row:",element2)
EXAMPLE CODE

• import numpy as np

# create a 2D array
• array1 = np.array([[1, 3, 5],[7, 9, 2],[4, 6, 8]])

# access the second row of the array


• second_row = array1[1, :]
• print("Second Row:", second_row) # Output: [7 9 2]
• # access the third column of the array
• third_col = array1[:, 2]
• print("Third Column:", third_col) # Output: [5 2 8]
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 CODE

• import numpy as np

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

print(arr[1:5])

Note: The result includes the start index, but excludes the end index.
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:])
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])
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])
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])
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])
VIEW OF ARRAY IN NUMPY

• The view is just a view of the original ndarray and the view does not
own the data.
• You can create an array view using the view() function of the
NumPy library.
• This is also known as Shallow Copy.
• 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.
• Example: Making a view and changing the original array
EXAMPLE CODE

import numpy as np
# creating array
arr = np.array([2, 4, 6, 8, 10])
# creating view
v = arr.view()
# 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)
COPY OF ARRAY IN NUMPY

• The copy is completely a new array and the copy owns the data.
• You can create a copy of an array using the copy() function of the
NumPy library.
• This is also known as Deep Copy.
• 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.
• Example: Making a copy and changing the original array
EXAMPLE CODE

import numpy as np

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

# creating copy of array


c = arr.copy()

# 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)
EXAMPLE: CHECK IF THE ARRAY IS A VIEW OR COPY

import numpy as np
# creating array
arr = np.array([2, 4, 6, 8, 10])
# creating copy of array
c = arr.copy()
# creating view of array
v = arr.view()
# printing base attribute of copy and view
print(c.base)
print(v.base)

You might also like