[Numpy-discussion] Can't seem to use np.insert() or np.append() for structured arrays

Benjamin Root ben.root at ou.edu
Fri Aug 29 22:10:34 EDT 2014


Consider the following:

a = np.array([(1, 'a'), (2, 'b'), (3, 'c')], dtype=[('foo', 'i'), ('bar',
'a1')])
b = np.append(a, (4, 'd'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File
"/home/ben/miniconda/lib/python2.7/site-packages/numpy/lib/function_base.py",
line 3555, in append
    return concatenate((arr, values), axis=axis)
TypeError: invalid type promotion
b = np.insert(a, 4, (4, 'd'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File
"/home/ben/miniconda/lib/python2.7/site-packages/numpy/lib/function_base.py",
line 3464, in insert
    new[slobj] = values
ValueError: could not convert string to float: d

In my original code snippet I was developing which has a more involved
dtype, I actually got a different exception:
b = np.append(a, c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File
"/home/ben/miniconda/lib/python2.7/site-packages/numpy/lib/function_base.py",
line 3553, in append
    values = ravel(values)
  File
"/home/ben/miniconda/lib/python2.7/site-packages/numpy/core/fromnumeric.py",
line 1367, in ravel
    return asarray(a).ravel(order)
  File
"/home/ben/miniconda/lib/python2.7/site-packages/numpy/core/numeric.py",
line 460, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

Luckily, this works as a work-around:
>>> b = np.append(a, np.array([(4, 'd')], dtype=a.dtype))
>>> b
array([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')],
      dtype=[('foo', 'i'), ('bar', 'S1')])

The same happens whether I enclose the value with square bracket or not. I
suspect that this array type just wasn't considered when its checking logic
was developed. This is with 1.8.2 from miniconda. Should we consider this a
bug or are structured arrays just not expected to be modified like this?

Cheers!
Ben Root
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20140829/3fd4a5cc/attachment.html>


More information about the NumPy-Discussion mailing list