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 the first (i.e. the
c1
-th) column to swap.c2 (int) – Index of the second (i.e. the
c2
-th) column 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
c1
-th andc2
-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]]