0

I happen to come across the term:

np.array([[0. for _ in range(20)] for _ in range(50)])

It gives me all 0.0 for a matrix of 20 x 50.

However, I don't like this syntax. I am wondering if there alternative way of doing this? I want 0 to be 0.0 (as float).

Thanks

1
  • Try [[0.0 for i in range(3)] for j in range(5)]]. That's basic Python list comprehension. Don't be thrown by the use of _. Next try [[(i,j) for i in range(3)] for j in range(5)]]. The array part is just like np.array([[1,2],[3,4]]). Commented Feb 21, 2017 at 2:02

2 Answers 2

2
np.zeros((20, 50), dtype=np.float32)  # or any other type; default: np.float64

Link to the Docs

Remark: no experienced numpy-user will use the approach in your example!

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

3 Comments

I won't understand the for _ in notation
But that was not the question right? You did ask for an alternative and i proposed the most natural. To answer your other question: the _ is nothing special. Many people use that to mark a variable which will nevber be used. You can call it x too without changing anything! The rest is basic python-stuff (iteration syntax).
@wrek You can find info about that here: stackoverflow.com/q/5893163/1394393. #3 in the accepted answer is what it's being used for here.
1
>>> a=np.zeros([5,8])
>>> a
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])
>>> type(a[1][1])
<type 'numpy.float64'>
>>>

You can see from the code that the default format is float64.

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.