Write a data string to a NumPy character array?

I want to write a data string to a NumPy array. Pseudocode:

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

Result:

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

How can this be done most naturally and efficiently with NumPy?

I don't need forloops, generators or anything iterative. Is it possible to do this with a single command, as with pseudo-code?

+5
source share
3 answers

Just make the text list(and not 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')
+3
source

No need to create a list when you have numpy.fromstring and numpy.fromiter.

+2
source

Python array. , list.

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

All Articles