1

Although I have seen some answers for this question, I was wondering if there's any better way to solve this problem.

For example,

N = 15
A = np.repeat(1/N, N)

if I do this the result will have shape (15, )

If I want the shape to be (15,1), I think I can do

A = np.repeat(1/N, N)[:,np.newaxis] 

I also have the same kind of problems with

np.ones(N); np.zeros(N)

and I can probably make the second dimension as 1, by using "np.newaxis"

But my question is, are there any better ways to do this?

6
  • Try A=A.reshape((15,1)) Commented Aug 13, 2017 at 17:15
  • Using np.newaxis is a good tool for this task (though I use the shorter None). There's a minimal speed penalty. The idiom is clear (to experienced users). And it is useful in many other circumstances. Commented Aug 13, 2017 at 17:17
  • @hpaulj , please explain me why is my explanation is not optimal? Commented Aug 13, 2017 at 17:19
  • As written your reshape needs to know the length of A. There is a -1 shortcut, which often puzzles beginners. Timings for a small task like this are tricky (we are just making a view), but newaxis times faster. But for me it's mainly a matter of readability. The purpose of newaxis is clear. Commented Aug 13, 2017 at 17:36
  • Technically a dimension of size 1 is not empty. Commented Aug 13, 2017 at 17:48

1 Answer 1

1

For np.ones and np.zeros you can pass a tuple specifying the shape of the output array:

np.ones((N, 1)); np.zeros((N, 1)) 

For np.repeat, you probably need to pass an array (or list) that already has two dimensions and then repeat along the desired axis:

>>> np.repeat([[1./N]], N, axis=0)
array([[ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667],
       [ 0.06666667]])

The syntax is, however, more difficult to read/understand, and promises no extra performances. You could stick to adding a new axis to the array like you've shown.

Sign up to request clarification or add additional context in comments.

2 Comments

Adding the extra dimensions to ones makes sense. Tweaking repeat like this is slower and harder to understand. np.full is faster.
@hpaulj Thanks for noting. Didn't actually time it to see which works faster. Added some comments about this.

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.