Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a data string to a NumPy character array?

Tags:

python

numpy

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?

like image 205
user213060 Avatar asked Nov 18 '09 21:11

user213060


2 Answers

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')
like image 67
Paul Avatar answered Oct 14 '22 14:10

Paul


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

like image 2
musicinmybrain Avatar answered Oct 14 '22 15:10

musicinmybrain