4.12. Array Iteration

4.12.1. 1-dimensional Array

import numpy as np


data = np.array([1, 2, 3])

for value in data:
    print(value)

# 1
# 2
# 3

4.12.2. 2-dimensional Array

import numpy as np


data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for value in data:
    print(value)

# [1 2 3]
# [4 5 6]
# [7 8 9]
import numpy as np


data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for row in data:
    for value in row:
        print(value)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

4.12.3. Flat

4.12.3.1. Flatten

import numpy as np


data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for value in data.flatten():
    print(value)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

4.12.3.2. Ravel

import numpy as np


data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for value in data.ravel():
    print(value)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

4.12.4. Enumerate

import numpy as np

data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for i, value in enumerate(data):
    print(i, value)

# 0 [1 2 3]
# 1 [4 5 6]
# 2 [7 8 9]
import numpy as np

data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for i, value in enumerate(data.ravel()):
    print(i, value)
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
# 5 6
# 6 7
# 7 8
# 8 9
import numpy as np

data = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for i, row in enumerate(data):
    for j, value in enumerate(row):
        print(i, j, value)

# 0 0 1
# 0 1 2
# 0 2 3
# 1 0 4
# 1 1 5
# 1 2 6
# 2 0 7
# 2 1 8
# 2 2 9

4.12.5. Assignments

4.12.5.1. Numpy Iteration

English
  1. Use data from "Input" section (see below)

  2. Use for to iterate over DATA

  3. Print even numbers

Polish
  1. Użyj danych z sekcji "Input" (patrz poniżej)

  2. Używając for iteruj po DATA

  3. Wypisz liczby parzyste

Input
DATA = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
The whys and wherefores
  • Iterating 2-dimensional ndarray

Hint
  • number % 2 == 0