How To Transpose 2D Array In Python
This Tutorial is about how to transpose a Two Dimensional Array in Python, The 2D array will contain both X-axis and Y-axis based on the positions the elements are arranged.
Array is the collection of similar data Types. Hence, these elements are arranged in X and Y axes respectively. The array() method will be implemented by using the NumPy module.
About NumPy Module:
Numerical Python (NumPy) has number of builtin methods. array() is one of the method.
- Array can hold many values based on single name.
- Access the elements based on the index number.
- We can slice the elements in the array [start:end] based on the start and end position -1 elements are display the results.
For an example x=NumPy.array([1,2]) # while slicing x[1:] the result will be .
Structure of Array
But in Python, the size will be taken dynamically and assign the index values to those elements. The elements are accessed based on the index values, If the array size is “n” the last index values is [n-1], The starting index always .
Also, read: Create 2D array from a list of lists in Python
Importing NumPy Module
Numpy module can be imported into the file by using the below command.
Usage of array
- Data must be a list or tuple or any data set.
- Array method converts the given data into an Array.
Example to Create an Array:
Lets have a look at the following example for Creation of an Array:
import numpy k=numpy.array([1,2,3]) print(k)
From the above example, [1,2,3] list is converted to Array by using NumPy module.
Python Program To Transpose 2D Array
import numpy k=2 l=[[1,1],[2,2]] l=numpy.array(l) for i in range(0,k): for j in range(0,k): print(numpy.array(l[i][j]),end=" ") print("") for i in range(0,k-1): for j in range(i,k): l[i][j],l[j][i]=l[j][i],l[i][j] for i in range(0,k): for j in range(0,k): print(numpy.array(l[i][j]),end=" ") print("")
The output of the above code:
1 1 2 2 1 2 1 2
- The input “k” will taken value=2. It will consider as NxN matrix.
- Based on for loop Elements are assign into a list.
- The list l will converted as Array.
- Based on Swapping Technique and elements are Swap their Positions.
Further references about NumPy study NumPy documentation->click here