WKW
WKW

Reputation: 77

numpy array with the second dimension empty

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?

Upvotes: 1

Views: 798

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

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.

Upvotes: 1

Related Questions