wrek
wrek

Reputation: 1161

Python for loop in numpy

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

Upvotes: 0

Views: 424

Answers (2)

Statham
Statham

Reputation: 4118

>>> 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.

Upvotes: 1

sascha
sascha

Reputation: 33542

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!

Upvotes: 2

Related Questions