swap_rows

pyhelpers.ops.swap_rows(array, r1, r2, as_list=False)[source]

Swap positions of two rows in an array.

Parameters:
  • array (numpy.ndarray) – an array

  • r1 (int) – index of a row

  • r2 (int) – index of another row

  • as_list (bool) – whether to return a list

Returns:

a new array/list in which the positions of the r1-th and r2-th rows are swapped

Return type:

numpy.ndarray | list

Examples:

>>> from pyhelpers.ops import swap_rows
>>> from pyhelpers._cache import example_dataframe

>>> example_arr = example_dataframe(osgb36=True).to_numpy(dtype=int)
>>> example_arr
array([[406705, 286868],
       [530039, 180371],
       [383830, 398113],
       [430147, 433553]])

>>> # Swap the 0th and 1st rows
>>> new_arr = swap_rows(example_arr, r1=0, r2=1)
>>> new_arr
array([[406705, 286868],
       [530039, 180371],
       [383830, 398113],
       [430147, 433553]])

>>> new_list = swap_rows(example_arr, r1=0, r2=1, as_list=True)
>>> new_list
[[406705, 286868], [530039, 180371], [383830, 398113], [430147, 433553]]