0

If I have a numpy ndarray of dtype string:

from numpy import array as narray
a = narray(['a', 'b'])

how do I add another string to it? And how do I access that string via an index?

Superdooperhero
  • 7,584
  • 19
  • 83
  • 138

1 Answers1

2

Check out http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html

For example,

numpy.insert( a, 2, 'c' )

would insert c at position 2 in a.

danmcardle
  • 2,079
  • 2
  • 17
  • 25
  • Do you need to do a = numpy.insert(a, 2, 'c')? Is this really inefficient due to python having to reallocate space every time? – Superdooperhero Mar 09 '13 at 22:26
  • 1
    @Superdooperhero - you're right about reallocating space every time. Numpy is not well equipped to deal with arrays that change their length. Try to build your entire set of data in advance using lists before giving it to Numpy to do your calculations. See, for example, [this question](http://stackoverflow.com/questions/2641691/building-up-an-array-in-numpy-scipy-by-iteration-in-python). – Benjamin Hodgson Mar 09 '13 at 22:32
  • 1
    Well I provided the simplest use case. Follow the documentation link and it says that `obj` may be a list of indices and `values` may be a list of values, so any number of inserts could be accomplished in one step. That's about as good as it's gonna get in python. – danmcardle Mar 09 '13 at 22:34