2

I have a numpy array of shape (6, 100, 161). I want to convert it to (600, 161) and then trim 16 from the end, so it's (584, 161)?

2 Answers 2

3

You can call reshape followed by slicing

import numpy as np

a = np.zeros((6,100,161))

b = a.reshape(600,161)[:-16,:]

b.shape

out: (584,161)
Sign up to request clarification or add additional context in comments.

Comments

3

You can use np.reshape:

>>> import numpy as np
>>> x = np.ones((6,100,161))
>>> x = x.reshape((-1, 161))
>>> x = x[:584, :]
>>> x.shape
(584, 161)

Here -1 works like this:

If the original shape was (x, y, z)

then if you write reshape(-1, z)

It infers that you want to dimensions, as you have given two numbers -1 and z, but you have specified size for only 1 dimension (i.e. z), so it infers the other size must be all that remains.

So total number of elements x * y * z, now after reshaping the number of elements must be same. You have specified you want z number of columns, so the number of rows must be x * y * z / z == x * y. -1 facilitates this.

For example:

>>> x = np.ones((3,4,3))
# number of elements = 3 * 4 * 3 == 36
>>> y = x.reshape(9, -1)
# you say you want 9 rows, so remaining elements 
# would be, 36 / 9 == 4, so no. of cols == 4
>>> y.shape
(9, 4)

2 Comments

Can you explain what the (-1, 161) does please?
x[:584, 161] will throw an error. Should either be x[:584, :161] or x[:584, :]

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.