Indexing & Slicing in NumPy (Access Data Like a Pro)

๐Ÿ“Œ Introduction

Accessing data is one of the most important skills when working with NumPy.

NumPy provides powerful ways to:

  • Access elements
  • Extract subsets
  • Modify data efficiently

๐Ÿ”ข What is Indexing?

Indexing means accessing a specific element using its position.


๐Ÿงช 1. Indexing in 1D Array

import numpy as nparr = np.array([10, 20, 30, 40])
print(arr[0])

๐Ÿ‘‰ Output:

10

โœ” Index starts from 0


๐Ÿ“Š 2. Indexing in 2D Array

import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr[1, 2])

๐Ÿ‘‰ Output:

6

โœ” Format:

arr[row, column]

๐Ÿ”ช What is Slicing?

Slicing means extracting a portion of an array.


โœ‚๏ธ 3. Slicing in 1D Array

arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])

๐Ÿ‘‰ Output:

[20 30 40]

โœ” Syntax:

arr[start:end]

๐Ÿ“ 4. Slicing in 2D Array

arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr[0:2, 1:3])

๐Ÿ‘‰ Output:

[[2 3]
[5 6]]

โœ” Format:

arr[row_start:row_end, col_start:col_end]

๐Ÿ” 5. Step Slicing

arr = np.array([10, 20, 30, 40, 50])
print(arr[::2])

๐Ÿ‘‰ Output:

[10 30 50]

โœ” Skips elements using step value


๐Ÿ”„ Modifying Values

arr = np.array([10, 20, 30])
arr[1] = 99
print(arr)

๐Ÿ‘‰ Output:

[10 99 30]

โš ๏ธ Important Note (View vs Copy)

Slicing does not create a copy, it creates a view.

๐Ÿ‘‰ Changing slice affects original array.


๐Ÿ“Š Summary Table

ConceptExample
Indexingarr[0]
2D Indexingarr[1,2]
Slicingarr[1:4]
Steparr[::2]

๐Ÿง  Pro Tips

  • Use slicing for fast data extraction
  • Combine indexing + slicing for powerful queries
  • Always be careful with modifying slices

๐Ÿ”— Used in Real Applications

Indexing & slicing are heavily used in:

  • Pandas
  • TensorFlow
  • Scikit-learn

๐Ÿ”š Conclusion

Mastering indexing and slicing in NumPy gives you full control over your data.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *