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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 - 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.
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.

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.