Online Tutorials & Training Materials | STechies.com
Register Login

NumPy Indexing and Slicing Array

|| 0

NumPy Indexing and Slicing Array
Stechies

This tutorial explains step by step the following topics:

  • Indexing and Slicing
  • Iterating through arrays
  • Stacking together two arrays
  • Indexing with Boolean array

Indexing and Slicing

Please follow the steps below for indexing and slicing an array:

1. We will begin with indexing and slicing. Add a code n[0:2].

2. Add the code n[-1] to bring up the last element.

3. Numpy array supports similar kind of slicing, create an array –

4. You can also re-use the index.

5. Add a multidimensional array 

6. Now when you add the code a[1, 2] it indicates the row and the column respectively.

7. Next add the code [0:2, 2]. It will bring up the respective 2nd elements from the 1st and the 2nd row.

8. Some more examples, the first number represents the row while the second represents the column.

9. If you print the 2nd and the 3rd columns then add [:, 1:3]

Iterate Through an Array

1. To iterate through an array

2.You can flatten the cells and then print them

Stack Two Arrays Together

To stack two arrays together vertically

.You can also horizontally stack two arrays –

Initialize a New Array

1. To spilt them horizontally, use the command 'np.hsplit' (a,3)

2. Store the result into a variable and then print it out one by one.

3. You can also split the arrays vertically.

4. Initialize an array and reshape it to your specifications.

5. Next add a conditional statement b = a > 4

6. To print all the values that are true –

7. Replacing all the elements greater than 4 with -1


Related Articles