bbestul
bbestul

Reputation: 359

Numpy Zeros and String Data Type

I have an 18x18 grid of Numpy Zeros and I have 1's and 2's randomly filling the board using the code below.

import numpy as np
a=np.zeros(324)
p=np.random.permutation(324)
a[p[:30]]=1
a[p[30:60]]=2
a.reshape(18,18)

And it returns the correct numpy array. However, I want to add a random X in there so I changed the first line of the code above to look like

a=np.zeros(324,dtype=str)

However, when I run the code, all of the zeros in the array disappears. It just shows up as '_'(without the underscore). Any thoughts to be able to have strings in the array but also have zeros?

Or a better way to create an 18x18 grid that can have strings in it?

Upvotes: 3

Views: 15356

Answers (1)

hpaulj
hpaulj

Reputation: 231375

A 'zero' for dtype=str is a blank, not 0 or even '0':

In [1]: a = np.zeros((3,3))
In [2]: a
Out[2]: 
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
In [3]: a = np.zeros((3,3),int)
In [4]: a
Out[4]: 
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])
In [5]: a = np.zeros((3,3),bool)
In [6]: a
Out[6]: 
array([[False, False, False],
       [False, False, False],
       [False, False, False]], dtype=bool)
In [7]: a = np.zeros((3,3),str)
In [8]: a
Out[8]: 
array([['', '', ''],
       ['', '', ''],
       ['', '', '']],
      dtype='<U1')

Often it is better to specify the string length as well, but you still get blanks:

In [9]: a = np.zeros((3,3),'U4')
In [10]: a
Out[10]: 
array([['', '', ''],
       ['', '', ''],
       ['', '', '']],
      dtype='<U4')

You could convert an integer array to string, and add other string values:

In [11]: a = np.zeros((3,3),int)
In [12]: a[[0,1,2],[2,0,1]] = [1,2,3]
In [13]: a
Out[13]: 
array([[0, 0, 1],
       [2, 0, 0],
       [0, 3, 0]])
In [14]: A = a.astype(str)
In [15]: A
Out[15]: 
array([['0', '0', '1'],
       ['2', '0', '0'],
       ['0', '3', '0']],
      dtype='<U11')
In [16]: A[[0,1,2],[0,1,2]] = 'X'
In [17]: A
Out[17]: 
array([['X', '0', '1'],
       ['2', 'X', '0'],
       ['0', '3', 'X']],
      dtype='<U11')

The original 0s turn into string '0'.

Upvotes: 4

Related Questions