Python Tutorial: Numpy-Indexing and Slicing array

Sunday, 4 July 2021

Numpy-Indexing and Slicing array

 Indexing and Slicing Array

#Program

import numpy as np

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

print(ar)

Output:

                [1 2 3 4]

Index Position 

0

1

2

3

1

2

3

4

 



#Program : Indexing 2D Array   

            Ar[Row,Column]

                Import numpy as np

                ar=np.array([1,2,3]

      [4,5,6],

      [7,8,9])

                print(ar[2,1])                     

                print(ar[2])                          #It will pick a row----[7,8,9]

                print(ar[:,1])                        #ar[row,column]---> output : [2,5,8]

                     Column

1

2

3

4

5

6

7

8

9

[0,0]

[0,1]

[0,2]

1

2

3

[1,0]

[1,1]

[1,2]

4

5

6

[2,0]

[2,1]

[2,2]

7

8

9

Array Slice

<array>[Start:Stop:Step, Start:Stop:Step]

                                                        Row Slicing            Column Slicing

                                                            Parameter           Parameter

#Program

import numpy as np

ar=np.array([[10,11,12,13,14],

            [15,16,17,18,19],

             [20,21,22,23,24],

             [25,26,27,28,29]])

print(“Print Original Value :”)

print(ar)

print("Print Second Row & Third Column Values :")

print(ar[1:,2:4])

print("Print I & III Rows and III & IV Columns Values :")

print(ar[1:3,2:4])

print("Print I & III Rows and I and III Column values :")

print(ar[0::2,0::2])

print("Print II & IV Rows and II & V Column Values: ")

print(ar[1::2,2::2])

print("I & III Rows and III and IV Column values: ")

print(ar[1::2,2:4:1])

 

Output:

Print Original Values :

[[10 11 12 13 14]

 [15 16 17 18 19]

 [20 21 22 23 24]

 [25 26 27 28 29]]

Print Second Row & Third Column Values :

[[17 18]

 [22 23]

 [27 28]]

Print I & III Rows and III & IV Columns Values :

[[17 18]

 [22 23]]

Print I & III Rows and I and III Column values :

[[10 12 14]

 [20 22 24]]

Print II & IV Rows and II & V Column Values:

[[17 19]

 [27 29]]

I & IV Rows and III and IV Column values:

[[17 18]

 [27 28]]

Print Original Value :

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

 print(ar[1:,2:4])

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

 print(ar[1:3,2:4])

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

print(ar[0::2,0::2])

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

 print(ar[1::2,2::2])

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

 print(ar[1::2,2:4:1])

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

 

No comments:

Post a Comment