Skip to content

Commit 5280fb0

Browse files
Create numpy_array_iteration.md
Added Introduction Added Methods Added examples Added Conclusion
1 parent b31bfc6 commit 5280fb0

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# NumPy Array Iteration
2+
3+
Iterating over arrays in NumPy is a common task when processing data. NumPy provides several ways to iterate over elements of an array efficiently.
4+
Understanding these methods is crucial for performing operations on array elements effectively.
5+
6+
## 1. Basic Iteration
7+
8+
- Iterating using basic `for` loop.
9+
10+
**Single-dimensional array iteration**:
11+
12+
Iterating over a single-dimensional array is straightforward using a basic `for` loop
13+
14+
```python
15+
import numpy as np
16+
17+
arr = np.array([1, 2, 3, 4, 5])
18+
for i in arr:
19+
print(i)
20+
```
21+
**Output** :
22+
```python
23+
[ 1 2 3 4 5 ]
24+
```
25+
**Multi-dimensional array**:
26+
27+
Iterating over multi-dimensional arrays, each iteration returns a sub-array along the first axis.
28+
29+
```python
30+
marr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
31+
32+
for arr in marr:
33+
print(arr)
34+
```
35+
**Output** :
36+
```python
37+
[1 2 3]
38+
[4 5 6]
39+
[7 8 9]
40+
```
41+
42+
## 2. Iterating with nditer
43+
44+
- `nditer` is a powerful iterator provided by NumPy for iterating over multi-dimensional arrays.
45+
- In each interation it gives each element.
46+
47+
```python
48+
import numpy as np
49+
50+
arr = np.array([[1, 2, 3], [4, 5, 6]])
51+
for i in np.nditer(arr):
52+
print(i)
53+
```
54+
**Output** :
55+
```python
56+
1
57+
2
58+
3
59+
4
60+
5
61+
6
62+
```
63+
64+
## 3. Iterating with ndenumerate
65+
66+
- `ndenumerate` allows you to iterate with both the index and the value of each element.
67+
- It gives index and value as output in each iteration
68+
69+
```python
70+
import numpy as np
71+
72+
arr = np.array([[1, 2], [3, 4]])
73+
for index,value in np.ndenumerate(arr):
74+
print(index,value)
75+
```
76+
77+
**Output** :
78+
79+
```python
80+
(0, 0) 1
81+
(0, 1) 2
82+
(1, 0) 3
83+
(1, 1) 4
84+
```
85+
86+
## 4. Iterating with flat
87+
88+
- The `flat` attribute returns a 1-D iterator over the array.
89+
-
90+
91+
```python
92+
import numpy as np
93+
94+
arr = np.array([[1, 2], [3, 4]])
95+
for element in arr.flat:
96+
print(element)
97+
```
98+
99+
**Output** :
100+
101+
```python
102+
1
103+
2
104+
3
105+
4
106+
```
107+
108+
Understanding the various ways to iterate over NumPy arrays can significantly enhance your data processing efficiency.
109+
Whether you are working with single-dimensional or multi-dimensional arrays, NumPy provides versatile tools to iterate and manipulate array elements effectively.

0 commit comments

Comments
 (0)