4.14. Array Sort

4.14.1. Sort

4.14.1.1. One dimensional

import numpy as np


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

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

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

4.14.1.2. Two dimensional - Default axis

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]])

4.14.1.3. Two dimensional - Columns

import numpy as np


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

a.shape
# (2, 3)

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

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

4.14.1.4. Two dimensional - Rows

import numpy as np

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

a.shape
# (3,3)

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

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

4.14.2. 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]])

4.14.3. Assignments

4.14.3.1. Sort

  • Complexity level: easy

  • Lines of code to write: 6 lines

  • Estimated time of completion: 5 min

  • Solution: solution/numpy_sort.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. 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. Wypisz a