3.13. Array Methods

3.13.1. Copy

import numpy as np


a = np.array([1, 2, 3])
b = a
c = a.copy()

a[0] = 99

repr(a)
# array([99, 2, 3])

repr(b)
# array([99, 2, 3])

repr(c)
# array([1, 2, 3])

3.13.2. Put

import numpy as np


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

a.put([0, 2], 99)
# array([99,  2, 99])
import numpy as np


a = np.array([1, 2, 3])
at_index = [0, 2]

a.put(at_index, 99)
# array([99,  2, 99])
import numpy as np


a = np.array([1, 2, 3])
b = np.array([99, 88, 77])
at_index = [0, 2]

a.put(at_index, b)
# array([99,  2, 88])

3.13.3. Fill

  • Modifies inplace

import numpy as np


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

a.fill(0)
# array([0, 0, 0])
import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6]])

a.fill(0)
# array([[0, 0, 0],
#        [0, 0, 0]])

3.13.4. Transpose

  • a.transpose() or a.T

  • a.transpose() is preferred

import numpy as np


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

a.transpose()
# array([1, 2, 3])
import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6]])

a.transpose()
# array([[1, 4],
#        [2, 5],
#        [3, 6]])

a.T
# array([[1, 4],
#        [2, 5],
#        [3, 6]])
import numpy as np


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

a.transpose()
# array([[1, 4, 7],
#        [2, 5, 8],
#        [3, 6, 9]])

3.13.5. Sort

import numpy as np


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

sorted(a)
# [1, 2, 3]

a.sort()
# array([1, 2, 3])
import numpy as np


a = np.array([[2, 3, 1],
              [5, 6, 4]])

sorted(a)
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

a.sort()
# array([[1, 2, 3],
#        [4, 5, 6]])

a.sort(axis=0)
# array([[2, 3, 1],
#        [5, 6, 4]])

a.sort(axis=1)
# array([[1, 2, 3],
#        [4, 5, 6]])

3.13.6. Flip

  • Does not modify inplace

  • Returns new ndarray

  • Reverse the order of elements in an array along the given axis

import numpy as np


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

np.flip(a)
# array([3, 2, 1])
import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6]])

a.flip()
# array([[6, 5, 4],
#        [3, 2, 1]])

np.flip(a, axis=0)
# array([[4, 5, 6],
#        [1, 2, 3]])

np.flip(a, axis=1)
# array([[3, 2, 1],
#        [6, 5, 4]])

3.13.7. To list

import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6]])

a.tolist()
# [[1, 2, 3], [4, 5, 6]]

3.13.8. Assignments

3.13.8.1. Methods

  • Complexity level: easy

  • Lines of code to write: 6 lines

  • Estimated time of completion: 5 min

  • Filename: solution/numpy_methods.py

English
  1. Set random seed to zero

  2. Generate a: ndarray of 12 random integers from 0 to 100 (exclusive)

  3. Reshape a to 3x4

  4. Sort a in columns

  5. Transpose a

  6. Print a

Polish
  1. Ustaw ziarno losowości na zero

  2. Wygeneruj a: ndarray z 12 losowymi liczbami całkowitymi od 0 do 100 (rozłącznie)

  3. Zmień kształt na 3x4

  4. Posortuj a w kolumnach

  5. Transponuj a

  6. Wypisz a