swap_cols

pyhelpers.ops.swap_cols(array, c1, c2, as_list=False)[source]

Swap positions of two columns in an array.

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

  • c1 (int) – index of a column

  • c2 (int) – index of another column

  • as_list (bool) – whether to return a list

Returns:

a new array/list in which the positions of the c1-th and c2-th columns are swapped

Return type:

numpy.ndarray | list

Examples:

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

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

>>> # Swap the 0th and 1st columns
>>> new_arr = swap_cols(example_arr, c1=0, c2=1)
>>> new_arr
array([[180371, 530039],
       [286868, 406705],
       [398113, 383830],
       [433553, 430147]])

>>> new_list = swap_cols(example_arr, c1=0, c2=1, as_list=True)
>>> new_list
[[180371, 530039], [286868, 406705], [398113, 383830], [433553, 430147]]