swap_rows

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

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 or list

Examples:

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

>>> example_arr = example_dataframe().to_numpy(dtype=int)
>>> example_arr
array([[530034, 180381],
       [406689, 286822],
       [383819, 398052],
       [582044, 152953]])

>>> # Swap the 0th and 1st rows
>>> new_arr = swap_rows(example_arr, r1=0, r2=1)
>>> new_arr
array([[406689, 286822],
       [530034, 180381],
       [383819, 398052],
       [582044, 152953]])

>>> new_list = swap_rows(example_arr, r1=0, r2=1, as_list=True)
>>> new_list
[[406689, 286822], [530034, 180381], [383819, 398052], [582044, 152953]]