tags:

views:

438

answers:

3

I want to write a data string to a numpy array. Pseudo Code:

d=numpy.zeros(10,dtype=numpy.character)
d[1:6]='hello'

Example result:

d=
  array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
        dtype='|S1')

How can this be done with numpy most naturally and efficiently? I don't want for loops, generators, or anything iterative, can it be done with one command as with the pseudo code?

+1  A: 

Just explicitly make your text a list (rather than that it is iterable from Python) and Numpy will understand it automatically:

>>> text = 'hello'
>>> offset = 1
>>> d[offset:offset+len(text)] = list(text)
>>> d

array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],
      dtype='|S1')
Paul
Ugly and not in-place, but does work. Thanks.
I tried using an iter to avoid the memory overhead for huge strings. You will not believe what numpy did --- d[1:6]=iter('hello')
omg, that's why I told you to use a list in the first place...
Paul
A: 

There's little need to build a list when you have numpy.fromstring and numpy.fromiter.

I'm writing many strings to different positions on the same array.
A: 

What you might want to try is python's array type. It will not have as high an overhead as a list.

from array import array as pyarray
d[1:6] = pyarray('c', 'hello')
bpowah