numpy.swapaxes() – The NumPy swapaxis Python Function

Introduction to NumPy swapaxis Python Function

Guide to NumPy swapaxis Python Function – The numpy.swapaxes() function interchange two array axes.

Syntax: Syntax of the NumPy swapaxis function

numpy.swapaxes(arr, axis1, axis2)

Parameters:

  • arr : [array_like] input array.
  • axis1 : [int] First axis.
  • axis2 : [int] Second axis.

Return: [ndarray] In earlier NumPy versions, a view of arr is returned only if the order of the axes is changed, otherwise the input array is returned. For NumPy >= 1.10.0, if arr is a ndarray, then a view of arr is returned; otherwise, a new array is created.

Code Examples of NumPy swapaxis Python Function

Example 01:

# welcome to softhunt.net
# Python program explaining
# numpy.swapaxes() function

# importing numpy as np
import numpy as np

arr = np.array([[1, 2, 3, 4]])

softhunt = np.swapaxes(arr, 0, 1)

print (softhunt)

Output:

[[1]
 [2]
 [3]
 [4]]

Note: These programs will not run in online IDEs. Please test them on your systems to see how they operate.

Example 02:

# welcome to softhunt.net
# Python program explaining
# numpy.swapaxes() function

# importing numpy as np
import numpy as np

arr = np.array([[[0, 1], [4, 5]], [[2, 3], [6, 7]]])

softhunt = np.swapaxes(arr, 0, 2)

print (softhunt)

Output:

[[[0 2]
  [4 6]]

 [[1 3]
  [5 7]]]

Note: These programs will not run in online IDEs. Please test them on your systems to see how they operate.

FAQs

How do I flip axis in NumPy?

Flip an array vertically (axis=0). Flip an array horizontally (axis=1). flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m).

How do I swap rows in NumPy?

How to swap two rows of an array using numpy.

  • Step1 – Import the library. import numpy as np. …
  • Step2 – Defining random array. a = np.array([[4,3, 1],[5 ,7, 0],[9, 9, 3],[8, 2, 4]]) print(a)
  • Step3 – Swapping and visualizing output. a[[0, 2]] = a[[2, 0]] print(a) …
  • Step4 – Lets look at our dataset now.

How do I swap columns in NumPy?

following are the steps

  • Step1 – Import NumPy module.
  • Step2 – Create a NumPy array.
  • Step3 – Swap the column with Index.
  • Step4 – Print the Final array.

NumPy swapaxis Python: Conclusion

That’s all for the NumPy swapaxis python function if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.moveaxis() – The NumPy moveaxis Python Function
  2. numpy.rollaxis() – The NumPy rollaxis Python Function

Leave a Comment