Reputation: 41945
This is working:
In [49]: type([1, 2, 3])
Out[49]: list
In [50]: type(array([1, 2, 3]))
Out[50]: numpy.ndarray
In [52]: 1j*array([1, 2, 3])
Out[52]: array([ 0.+1.j, 0.+2.j, 0.+3.j])
When I try to do this on my own list asdf
:
In [46]: type(asdf)
Out[46]: list
In [47]: type(array(asdf))
Out[47]: numpy.ndarray
In [48]: 1j*array(asdf)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-dd0d8b4948e8> in <module>()
----> 1 1j*array(asdf)
TypeError: unsupported operand type(s) for *: 'complex' and 'numpy.ndarray'
The multiplication seemed happy with the short list, what could possibly go wrong for asdf
? It is rather large, 20347 elements, but that shouldn't matter?
Upvotes: 1
Views: 559
Reputation: 231385
The Python interpreter translates *
to a call to __mul__
(or one of its variants). And in the case of 3 * obj
, it will use the method of the obj
.
Building on your comment that asdf
contains strings:
In [205]: A=np.array(['A','B','C'])
In [206]: B=np.array([1,2,3])
In [207]: B.__mul__(3)
Out[207]: array([3, 6, 9])
In [208]: A.__mul__(3)
Out[208]: NotImplemented
For the array of strings the method returns 'NotImplemented', without saying anything about why. That probably is why the error message says numpy.array
, the type of A
, rather than the dtype
of A
. It's an interpreter error message, not a numpy
one.
There is a version of multiply
that works with strings:
In [213]: np.char.multiply(A,3)
Out[213]:
array(['AAA', 'BBB', 'CCC'],
But not with complex multipliers.
Upvotes: 2