Skip to content

Commit 5d0c074

Browse files
Update Indexing_slicing.py
1 parent 85f78bb commit 5d0c074

File tree

1 file changed

+122
-88
lines changed

1 file changed

+122
-88
lines changed
Lines changed: 122 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -1,120 +1,154 @@
1-
import numpy as np
21

3-
# Creating a 1D NumPy array
4-
arr_1d = np.array([1.4, 2, 3.7, 4, 5, 6])
2+
# 🔍 NumPy Indexing, Slicing, and Filtering
53

6-
# Creating a 2D NumPy array (3x3 matrix)
7-
arr_2d = np.array([[1, 2, 30],
8-
[4, 50, 6],
9-
[70, 8, 9]])
4+
This repository demonstrates how to access and manipulate data in NumPy arrays using **indexing**, **slicing**, **fancy indexing**, and **boolean masking** techniques. These operations are essential for data manipulation and form the backbone of most data science and numerical computing workflows.
105

11-
# ----------------------------------------
12-
# INDEXING
13-
# ----------------------------------------
14-
# Indexing in NumPy:
15-
# For 1D arrays: arr[index]
16-
# For 2D arrays: arr[row, column]
6+
---
177

18-
# Example:
19-
# print(arr_1d[2]) # Access 3rd element (3.7)
20-
# print(arr_2d[1,2]) # Access value at 2nd row, 3rd column (6)
8+
## 📘 Table of Contents
219

10+
1. [Introduction](#introduction)
11+
2. [Indexing](#indexing)
12+
3. [Slicing](#slicing)
13+
4. [2D Array Slicing](#2d-array-slicing)
14+
5. [Fancy Indexing](#fancy-indexing)
15+
6. [Boolean Masking & Filtering](#boolean-masking--filtering)
16+
7. [Using `np.where`](#using-npwhere)
17+
8. [Conclusion](#conclusion)
2218

23-
# ----------------------------------------
24-
# SLICING
25-
# ----------------------------------------
26-
# General form: arr[start:stop:step]
27-
# Note: 'stop' index is excluded
19+
---
2820

29-
first = arr_1d[1:4] # Slicing from index 1 to 3 (i.e., 2, 3.7, 4)
30-
second = arr_1d[:4] # From start to index 3 (i.e., 1.4 to 4)
31-
third = arr_1d[::2] # Every second element (step size 2)
32-
fourth = arr_1d[::-1] # Reversing the array using negative step
21+
## 📌 Introduction
3322

34-
print("First slice:", first)
35-
print("Second slice:", second)
36-
print("Third slice:", third)
37-
print("Reversed array:", fourth)
23+
NumPy is a foundational Python library used for efficient numerical operations. Understanding how to access and modify elements in arrays is key to working with NumPy. This guide walks through examples that explain:
3824

25+
- Accessing single and multiple values
26+
- Selecting slices or subarrays
27+
- Applying conditional logic to filter data
3928

40-
# ----------------------------------------
41-
# 2D ARRAY INDEXING AND SLICING
42-
# ----------------------------------------
29+
---
4330

44-
# Accessing a specific row in a 2D array
45-
# Example: Second row (index 1)
46-
print('Second row:', arr_2d[1])
31+
## 🧹 Indexing
4732

48-
# Accessing a specific column in a 2D array
49-
# Example: Third column (index 2)
50-
print('Third column:', arr_2d[:, 2])
33+
### 1D Array
34+
```python
35+
arr[index]
36+
```
5137
52-
# Extracting a sub-array using slicing
53-
# Syntax: arr[row_start:row_end, col_start:col_end]
54-
# Example: Extracts rows 0–2 and columns 1–2 (excluding row 3 and column 3)
55-
sub_array = arr_2d[0:3, 1:3]
56-
print("2D Sliced Sub-array:\n", sub_array)
38+
### 2D Array
39+
```python
40+
arr[row, column]
41+
```
5742

43+
🔹 Example:
44+
```python
45+
arr_1d = np.array([1.4, 2, 3.7, 4, 5, 6])
46+
arr_2d = np.array([[1, 2, 30], [4, 50, 6], [70, 8, 9]])
5847

59-
# ----------------------------------------
60-
# FANCY INDEXING
61-
# ----------------------------------------
62-
# Select multiple specific elements by index
63-
print("Fancy indexing on 1D:", arr_1d[[0, 2, 4]]) # Fetch elements at index 0, 2, and 4
48+
print(arr_1d[2]) # Output: 3.7
49+
print(arr_2d[1, 2]) # Output: 6
50+
```
6451

52+
---
6553

66-
import numpy as np
54+
## ✂️ Slicing
6755

68-
# ----------------------------------------
69-
# BOOLEAN MASKING ON ARRAYS
70-
# ----------------------------------------
56+
### Syntax
57+
```python
58+
arr[start:stop:step]
59+
```
7160

72-
# Boolean masking to extract values based on a condition
73-
# Returns a 1D array of elements where the condition is True
74-
print("Boolean masking on 2D (elements > 25):", arr_2d[arr_2d > 25])
61+
🔹 Examples:
62+
```python
63+
first = arr_1d[1:4] # [2, 3.7, 4]
64+
second = arr_1d[:4] # [1.4, 2, 3.7, 4]
65+
third = arr_1d[::2] # [1.4, 3.7, 5]
66+
fourth = arr_1d[::-1] # [6, 5, 4, 3.7, 2, 1.4]
67+
```
7568

76-
# ----------------------------------------
77-
# FILTERING ELEMENTS FROM 1D ARRAY
78-
# ----------------------------------------
69+
---
7970

80-
# Create a 1D array
81-
numbers = np.array([1, 2, 0, 3, 5, 6, 7, 8, 9, 10, 12, 45, 68, 90])
71+
## 🧩 2D Array Slicing
8272

83-
# Extract all even numbers using boolean masking
84-
even_numbers = numbers[numbers % 2 == 0]
85-
print("Even numbers:", even_numbers)
73+
You can slice rows and columns simultaneously:
74+
75+
```python
76+
print(arr_2d[1]) # Second row
77+
print(arr_2d[:, 2]) # Third column
78+
print(arr_2d[0:3, 1:3]) # Sub-array from rows 0-2 and columns 1-2
79+
```
80+
81+
---
82+
83+
## 🎯 Fancy Indexing
84+
85+
Fancy indexing lets you access multiple arbitrary indices at once.
86+
87+
```python
88+
print(arr_1d[[0, 2, 4]]) # Output: [1.4, 3.7, 5]
89+
```
90+
91+
---
92+
93+
## 🧪 Boolean Masking & Filtering
94+
95+
### Filtering 2D Array
96+
```python
97+
print(arr_2d[arr_2d > 25]) # Output: [30 50 70]
98+
```
8699
87-
# ----------------------------------------
88-
# FILTERING WITH MASK
89-
# ----------------------------------------
100+
### Filtering Even Numbers from 1D
101+
```python
102+
numbers = np.array([1, 2, 0, 3, 5, 6, 7, 8, 9, 10, 12, 45, 68, 90])
103+
even_numbers = numbers[numbers % 2 == 0]
104+
print(even_numbers) # Output: [ 2 0 6 8 10 12 68 90]
105+
```
90106
91-
# Create a boolean mask for elements greater than 5
107+
### Filtering with Boolean Mask
108+
```python
92109
mask = numbers > 5
93-
# Use the mask to filter values
94-
print("Numbers greater than 5:", numbers[mask])
110+
print(numbers[mask]) # Output: [ 6 7 8 9 10 12 45 68 90]
111+
```
112+
113+
---
95114

96-
# ----------------------------------------
97-
# FANCY INDEXING vs. np.where()
98-
# ----------------------------------------
115+
## 🧠 Using `np.where`
99116

100-
# np.where returns the indices where condition is True
117+
### Getting Indices of Elements Matching a Condition
118+
```python
101119
where_result = np.where(numbers > 5)
102-
print("Indices where numbers > 5:", where_result)
103-
print("Values at those indices:", numbers[where_result])
120+
print(where_result) # Output: (array([...]),)
121+
print(numbers[where_result]) # Output: [ 6 7 8 9 10 12 45 68 90]
122+
```
104123
105-
# np.where with 3 parameters: condition, value_if_true, value_if_false
106-
# This replaces numbers > 5 with number * 4, else keeps the number as-is
124+
### Conditional Replacement
125+
```python
107126
condition_array = np.where(numbers > 5, numbers * 4, numbers)
108-
print("Apply logic: numbers > 5 → number * 4 else keep same:\n", condition_array)
127+
print(condition_array)
128+
```
109129
110-
# np.where returning custom labels for each condition
130+
### Conditional Labeling
131+
```python
111132
condition_array2 = np.where(numbers > 5, "True", "False")
112-
print("Condition labels (True/False):", condition_array2)
113-
114-
# Equivalent pseudocode for the above logic:
115-
'''
116-
if numbers[i] > 5:
117-
result = numbers[i] * 4
118-
else:
119-
result = numbers[i]
120-
'''
133+
print(condition_array2)
134+
```
135+
136+
---
137+
138+
## ✅ Conclusion
139+
140+
This guide covered the core techniques for working with subsets of NumPy arrays:
141+
142+
- Indexing individual elements
143+
- Slicing ranges
144+
- Fancy indexing for custom selection
145+
- Boolean masks and conditionals for filtering
146+
147+
These skills are essential for data preprocessing and manipulation in any scientific or machine learning pipeline.
148+
149+
---
150+
151+
## 💡 Pro Tip
152+
153+
Practice modifying arrays and chaining these techniques to prepare for real-world data workflows.
154+

0 commit comments

Comments
 (0)