119

I'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. i.e. you can take a string str and keeping adding to it: str += "some stuff...". Is there a way to make an array of such strings?

When I try this, each element only stores a single character

strArr = numpy.empty(10, dtype='string')
for i in range(0,10)
    strArr[i] = "test"

On the other hand, I know I can initialize an array of certain length strings, i.e.

strArr = numpy.empty(10, dtype='s256')

which can store 10 strings of up to 256 characters.

2 Answers 2

169

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
5
  • 2
    Thanks, your first example is especially helpful--I never would have guessed that behavior! I'm not worried about the speed for this object, so slower access should be fine. Feb 1, 2013 at 4:25
  • 1
    Nice answer. I've incorporated a link to it with demo into a python notebook page I'm working on about numpy array creation. Mar 20, 2015 at 13:15
  • @senderle if an array is with object dtype, then np.fromstring(arr.tostring()) will fail with numpy Cannot create an object array from a string. Any ideas to solve this?
    – youkaichao
    Jul 31, 2018 at 13:58
  • @游凯超 hmm. That's a tough one. It's not a total surprise because numpy really isn't designed to work with python objects. It's more of a shortcut than a proper use of numpy. So there's no real reason for them to support corner cases like that. My approach would probably be to get the maximum length of string and use a standard fixed-width char array.
    – senderle
    Aug 6, 2018 at 22:36
  • @游凯超 if your goal is to use strings as row labels or column headers you should also look into structured arrays.
    – senderle
    Aug 6, 2018 at 22:43
24

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)
1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.