Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

Any input would be appreciated, thank you.

Post answer edit

The answer below is perfect when following the comments.

share|improve this question
    
possible duplicate of numpy array initialization (fill with identical values) –  aIKid Dec 11 '13 at 6:33
add comment

1 Answer

up vote 3 down vote accepted

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'
share|improve this answer
5  
I don't think np.where is necessary here (is it?). can't you just do arr[arr==''] = '0'? –  mgilson Dec 11 '13 at 6:35
    
Ah yep, good point! –  qmorgan Dec 11 '13 at 6:37
    
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 6:52
    
You need to index the first data as well. Try: data[:,1][data[:,1]==''] = '0' –  qmorgan Dec 11 '13 at 6:57
    
Awesome, that worked. Thank you, I tried using numpy.where() before but didn't use the index. –  bronstad Dec 11 '13 at 7:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.