Angry Coder
Angry Coder

Reputation: 82

How to transpose a 2D array using numpy?

I want to convert this array

[array([46, 64, 50, 66]),
 array([53, 61, 59, 59]),
 array([54, 63, 55, 61]),
 array([56, 58, 51, 55])]

into this array

[array([46, 53, 54, 56]),
 array([64, 61, 63, 58]),
 array([50, 59, 55, 51]),
 array([66, 59, 61, 55])]

Is there a way to do this in numpy?

Upvotes: 2

Views: 2110

Answers (2)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15568

Numpy allows you to transpose. Cast the list to numpy array and use .T

import numpy as np

case = [np.array([46, 64, 50, 66]),
 np.array([53, 61, 59, 59]),
 np.array([54, 63, 55, 61]),
 np.array([56, 58, 51, 55])]

# transform `[ ]` list to array and then `.T`
np.array(case).T # Transpose

See documentation of Transpose for more details.

Upvotes: 6

Azeem Lodhi
Azeem Lodhi

Reputation: 53

check out this python docs link for help Check for transpose function in numpy as follows https://numpy.org/doc/stable/reference/generated/numpy.transpose.html

Upvotes: 1

Related Questions