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 the first (i.e. the r1-th) row to swap.

  • r2 (int) – Index of the second (i.e. the r2-th) row to swap.

  • as_list (bool) – Whether to return a list instead of an array; defaults to False.

Returns:

A new array or list where 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]]