6

How to flatten this:

b = np.array([
    [[1,2,3], [4,5,6], [7,8,9]],
    [[1,1,1],[2,2,2],[3,3,3]]
])

into:

c = np.array([
    [1,2,3,4,5,6,7,8,9],
    [1,1,1,2,2,2,3,3,3]
])

Niether of these work:

c = np.apply_along_axis(np.ndarray.flatten, 0, b)
c = np.apply_along_axis(np.ndarray.flatten, 0, b)

Just returns the same array.

It would be great to flatten this in place.

3 Answers 3

8

This will do the job:

c=b.reshape(len(b),-1)

Then c is

array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])
Sign up to request clarification or add additional context in comments.

2 Comments

What -1 does in reshape ?
It's a shortcut to automatically calculate the size of that dimension. Since b.size = 18 and len(b) = 2, the -1 is calculated to be 18 / 2 = 9
2

You can completely flatten and then reshape:

c = b.flatten().reshape(b.shape[0],b.shape[1]*b.shape[2])

Output

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

Comments

0

So you could always just use reshape:

b.reshape((2,9)) 
array([[1, 2, 3, 4, 5, 6, 7, 8, 9],
       [1, 1, 1, 2, 2, 2, 3, 3, 3]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.