0

I have a list, say

a = [3, 4, 5, 6, 7]

And i want to create a numpy array of zeros of that list's length.

If I do

b = np.zeros((len(a), 1))

I get

[[0, 0, 0, 0, 0]]

instead of

[0, 0, 0, 0, 0]

What is the best way to get the latter option?

1
  • assuming it always returns data in this shape, you can just do b = np.zeros((len(a), 1))[0] Commented Jan 20, 2019 at 10:36

3 Answers 3

4

If you don't want to have to care about shapes, use np.zeros_like:

np.zeros_like(a)
# array([0, 0, 0, 0, 0])

There's also the option of querying np.shape:

np.zeros(np.shape(a))
# array([0., 0., 0., 0., 0.])

Both options should work for ND lists as well.

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

2 Comments

What do you mean by "don't want to care about shapes"? Why are the options different?
@Gulzar from your code, it seems like your grief was mostly because you could not initialise np.zeros with the correct shape. So my first option was to give you something that did not need explicit dealing with the shape at all—let numpy handle that.
4

You passed two-element tuple to zeros, so it produced 2D array, you can simply pass integer to zeros

a = [3, 4, 5, 6, 7]
b = np.zeros(len(a))
print(b) #prints [ 0.  0.  0.  0.  0.]

Comments

1

You can try this

np.zeros(len(a), dtype=np.int)

It will return

array([0, 0, 0, 0, 0])

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.