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 *