5

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

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 most naturally and efficiently with NumPy?

I don't want for loops, generators, or anything iterative. Can it be done with one command as with the pseudocode?

3 Answers 3

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

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')
2

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

1 Comment

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

You might try 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')

1 Comment

Note that in Python 3 this will not work, as it is a TypeError to try to instantiate a character array from a string, and you should try to use bytes instead. See this for more detail and a workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.