2.11. Array Sort

2.11.1. Sort

import numpy as np


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

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


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

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

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

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

2.11.2. Flip

  • Does not modify inplace

  • Returns new np.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]])

2.11.3. Assignments

Code 2.47. Solution
"""
* Assignment: Numpy Sort
* Complexity: easy
* Lines of code: 2 lines
* Time: 3 min

English:
    1. Define `result_sort` with sorted `DATA` by columns
    2. Define `result_flip` with flipped `DATA` by rows
    3. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result_sort` z posortowanym `DATA` po kolumnach
    2. Zdefiniuj `result_flip` z flipniętym `DATA` po wierszach
    3. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `.sort()` returns `None`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> type(result_sort) is np.ndarray
    True
    >>> type(result_flip) is np.ndarray
    True
    >>> result_sort
    array([[44, 47, 64, 67],
           [ 9, 21, 67, 83],
           [36, 70, 87, 88]])
    >>> result_flip
    array([[36, 70, 87, 88],
           [ 9, 21, 67, 83],
           [44, 47, 64, 67]])
"""

import numpy as np


DATA = np.array([[44, 47, 64, 67],
                 [67,  9, 83, 21],
                 [36, 87, 70, 88]])

result_sort = ...
result_flip = ...