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

Python Unit 5 (4 Program)

Uploaded by

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

Python Unit 5 (4 Program)

Uploaded by

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

4.

Python program to demonstrate basic slicing, integer and boolean indexing


import numpy as np

def demonstrate_indexing():

# Create a 2D array (matrix)

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

[5, 6, 7, 8],

[9, 10, 11, 12]])

print("Original 2D array:")

print(array_2d)

# Basic Slicing

print("\nBasic Slicing:")

print("First two rows and last two columns:")

sliced_array = array_2d[:2, 2:]

print(sliced_array)

# Integer Indexing

print("\nInteger Indexing:")

print("Element at row 1, column 2:")

print(array_2d[1, 2]) # Accessing the element at row 1, column 2 (7)

print("Elements from rows 0 and 2, and columns 1 and 3:")

indexed_array = array_2d[[0, 2], [1, 3]]

print(indexed_array)

# Boolean Indexing

print("\nBoolean Indexing:")

# Create a boolean mask

mask = array_2d > 6


print("Boolean mask (elements greater than 6):")

print(mask)

print("Elements greater than 6:")

boolean_indexed_array = array_2d[mask]

print(boolean_indexed_array)

if __name__ == "__main__":

demonstrate_indexing()

Output:

Original 2D array

[1 2 3 4]

[5 6 7 8]

[9 10 11 12]

Basic slicing

First two rows and last two columns 2:

[[3,4]

[7,8]]

Integer indexing:

Element at row1, column2:

Elements from rows 0 and 2, and columns lands [2,12]

Boolean indexing

Boolean mask [elements greater than 6]:

[(False False False False]

[False False True True)]


[True True True True)]

Elements greater than 6

[7,8, 9,10,11,12]

------code execution successful------

You might also like