# numpy.repeat TypeError: array cannot be safely cast to required type

Tim Hochberg tim.hochberg at ieee.org
Fri Nov 3 14:39:15 CST 2006

```George Sakkis wrote:
> Tim Hochberg wrote:
>
>
>> George Sakkis wrote:
>>
>>> Can anyone explain this ?
>>>
>>>
>>>
>>>>>> import numpy as N
>>>>>> x = N.arange(1,6,dtype='B')
>>>>>> x
>>>>>>
>>>>>>
>>> array([1, 2, 3, 4, 5], dtype=uint8)
>>>
>>>
>>>>>> N.repeat(x, N.ones(5,'H'))
>>>>>>
>>>>>>
>>> array([1, 2, 3, 4, 5], dtype=uint8)
>>>
>>>
>>>>>> N.repeat(x, N.ones(5,'l'))
>>>>>>
>>>>>>
>>> array([1, 2, 3, 4, 5], dtype=uint8)
>>>
>>>
>>>>>> N.repeat(x, N.ones(5,'L'))
>>>>>>
>>>>>>
>>> Traceback (most recent call last):
>>>   File "<stdin>", line 1, in ?
>>>   File
>>> "/usr/local/lib/python2.4/site-packages/numpy/core/fromnumeric.py",
>>> line 83, in repeat
>>>     return repeat(repeats, axis)
>>> TypeError: array cannot be safely cast to required type
>>>
>>>
>> It means you can't safely a value of type uint32 ('L') to a value of
>> type int32 ('i').  The second argument of repeat needs to be castable to
>> type int32.
>>
>
> I see. I suppose there is a better reason for this than a "why on earth
> would anyone repeat a value more than 2**32-1 times". Besides, why
> should it be castable to a signed type since we're talking about number
> of repetitions ?
>
I suspect it's just a matter of simplicity although I haven't looked at
the code in question. On the way in all of the arrays are going to need
to be cast to some standard integral type. While unit32 might make
sense, int32 is by far the more common type. If one was to use uint32 as
the type, before  casting int32 to uint32, one would have to scan the
array looking for negative values lest they get cast into really big
positive values. An analogous problem exists for casting uint32 to
int32, but since unit32 is rather uncommon, one can just make users do
the necessary checking and casting by hand and probably someone will
only notice every couple of years.

>> A style note: please use the named dtypes (int32, uint32, etc) rather
>> than the old-style letter codes; the former is much clearer. The answer
>> to your question might  have been immediately apparent had you been
>> using named dtypes.
>>
>
> I'm using numpy along with the struct module, so the letter codes are
> convenient for talking to both modules.
>
I imagine they are, but they're harder for me, and I suspect many
readers don't have to go look stuff up.

-tim

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier