John
John

Reputation: 2707

Get data array backing fortran ordered numpy array

So I understand that "fortran ordering" of a numpy array means it's stored column major, but doesn't actually affect what the data represents. What I'm looking for is a way to take a column major numpy array, and return a 1 dimensional array that is stored in the same order as numpy's internal column major representation.

For example, say I have an array like so, but it is stored in column major format.

array([[1, 2, 3],
       [4, 5, 6]])

Since it's column major, strides are (8, 16)

I would like a way to get the flat, column major representation, i.e.:

array([1, 4, 2, 5, 3, 6])

Upvotes: 0

Views: 80

Answers (1)

Mercury
Mercury

Reputation: 4171

Use .flatten with the argument F.

a = np.array([[1, 2, 3],
              [4, 5, 6]])

a.flatten('C') #row major
>>> [1, 2, 3, 4, 5, 6]

a.flatten('F') #column major
>>> [1, 4, 2, 5, 3, 6]

Transposing it and then making it flat is also another hacky way of doing it.

a.T.reshape(-1)
>>> [1, 4, 2, 5, 3, 6]

Upvotes: 1

Related Questions