vote up 0 vote down star

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?

flag

29% accept rate

3 Answers

vote up 1 vote down

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')
link|flag
Ugly and not in-place, but does work. Thanks. – user213060 Nov 18 at 22:22
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') – user213060 Nov 18 at 22:26
omg, that's why I told you to use a list in the first place... – Paul Nov 18 at 22:38
vote up 0 vote down

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

link|flag
I'm writing many strings to different positions on the same array. – user213060 Nov 25 at 15:08
vote up 0 vote down

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')
link|flag

Your Answer

Get an OpenID
or
never shown

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