Oceanescence
Oceanescence

Reputation: 2127

Creating Arrays in numpy using zeros

I've been trying to create a 6 by 6 array in python using the numpy module with all elements set as 0.0:

import numpy as np
RawScores = np.zeros((6,6), dtype=np.float)
print RawScores

This outputs:

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

Why are there no commas? Is it still an array without them?

Upvotes: 1

Views: 3074

Answers (2)

Charles Doutriaux
Charles Doutriaux

Reputation: 61

If you really really care about the commas you can always redefine the way numpy prints out arrays, VERY dirty example:

import numpy as np
RawScores = np.zeros((6,6), dtype=np.float)
def add_comma(num):
  return "%g, " % num

np.set_printoptions(formatter={"all":add_comma})
print RawScores
[[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, ]]

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 118001

It is because the print function calls the __str__ method, instead of the __repr__ method. See the following example. Please see here for a detailed explanation of the difference between these two methods.

# Python 2D List
>>> [[0]*6]*6
[[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]]

>>> import numpy as np
>>> np.zeros((6,6))
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.]])

# calls __repr__
>>> a = np.zeros((6,6))
>>> 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.]])

# calls __str__
>>> print a
[[ 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.]]

Upvotes: 3

Related Questions