5

I have an array in numpy, which was generated using np.array() from a python list so my entries are strings, but some of the values are blank. Here is an example array:

['1', '1', '1', '1']
['1', '1', '', '1']
['1', '1', '1', '1']
['1', '', '1', '1']

There is no 'NaN' or 'None', it is blank. I want to be able to fill all the blank cells in a particular column with the same value.

Shadow
  • 8,749
  • 4
  • 47
  • 57
bronstad
  • 67
  • 1
  • 1
  • 7
  • possible duplicate of [numpy array initialization (fill with identical values)](http://stackoverflow.com/questions/5891410/numpy-array-initialization-fill-with-identical-values) – aIKid Dec 11 '13 at 06:33

1 Answers1

6

You can use numpy.where() to achieve this.

In [8]: arr = numpy.array(['','1','2','3',''])

In [9]: arr[numpy.where(arr=='')] = '0'

In [10]: arr
Out[10]:
array(['0', '1', '2', '3', '0'],
      dtype='|S1')

Edit As @mgilson pointed out, you could just do:

arr[arr==''] = '0'
qmorgan
  • 4,794
  • 2
  • 19
  • 14
  • 7
    I don't think `np.where` is necessary here (is it?). can't you just do `arr[arr==''] = '0'`? – mgilson Dec 11 '13 at 06:35
  • I want to fill the blank cells of a particular column, not all blank cells. Say I use the code: arr[arr[0::,1]==''] = '0'. This turns any row with a blank in the 2nd column into all 0 entries, not just the blank. – bronstad Dec 11 '13 at 06:52
  • You need to index the first `data` as well. Try: `data[:,1][data[:,1]==''] = '0'` – qmorgan Dec 11 '13 at 06:57
  • Awesome, that worked. Thank you, I tried using numpy.where() before but didn't use the index. – bronstad Dec 11 '13 at 07:01