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

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
wrek
  • 1,061
  • 5
  • 14
  • 26
  • 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]])`. – hpaulj Feb 21 '17 at 02:02

2 Answers2

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!

sascha
  • 32,238
  • 6
  • 68
  • 110
  • I won't understand the `for _ in` notation – wrek Feb 21 '17 at 01:26
  • 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). – sascha Feb 21 '17 at 01:28
  • 1
    @wrek You can find info about that here: http://stackoverflow.com/q/5893163/1394393. #3 in the accepted answer is what it's being used for here. – jpmc26 Feb 21 '17 at 01:28
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.

Statham
  • 4,000
  • 2
  • 32
  • 45