How do I do the following without a for loop?
import numpy as np
l = np.array([[1, 3], 1, np.nan, [3, 53, 13], ['225gg2g']], dtype=object)
loc = [1, 2]
for i in loc:
l[i] = ['wgwg', 23, 'g']
How do I do the following without a for loop?
import numpy as np
l = np.array([[1, 3], 1, np.nan, [3, 53, 13], ['225gg2g']], dtype=object)
loc = [1, 2]
for i in loc:
l[i] = ['wgwg', 23, 'g']
In [424]: l = np.array([[1, 3], 1, np.nan, [3, 53, 13], ['225gg2g']], dtype=object)
In [425]: loc = [1,2]
In [426]: l[loc]
Out[426]: array([1, nan], dtype=object)
In [427]: l[loc] = ['wgwg',23,'g']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-427-53c5987a9ac6> in <module>()
----> 1 l[loc] = ['wgwg',23,'g']
ValueError: cannot copy sequence with size 3 to array axis with dimension 2
It's trying to broadcast the 3 item list (converted to an array?) into a 2 item slot.
We can wrap the list in another list, so it is now a single item list:
In [428]: l[loc] = [['wgwg',23,'g']]
In [429]: l
Out[429]:
array([list([1, 3]), list(['wgwg', 23, 'g']), list(['wgwg', 23, 'g']),
list([3, 53, 13]), list(['225gg2g'])], dtype=object)
Were as if we copy it one by one we get:
In [432]: l[loc[0]] = ['wgwg',23,'g']
In [433]: l[loc[1]] = ['wgwg',23,'g']
In [434]: l
Out[434]:
array([list([1, 3]), list(['wgwg', 23, 'g']), list(['wgwg', 23, 'g']),
list([3, 53, 13]), list(['225gg2g'])], dtype=object)
There isn't an easy to way to get around this 3=>2 mapping issue.
But why do you need to do this? It looks suspicious to me.
It works I first create a 0d object array:
In [444]: item = np.empty([], object)
In [445]: item.shape
Out[445]: ()
In [446]: item[()] = ['wgwg',23,'g']
In [447]: item
Out[447]: array(['wgwg', 23, 'g'], dtype=object)
In [448]: l[loc] = item
In [449]: l
Out[449]:
array([list([1, 3]), list(['wgwg', 23, 'g']), list(['wgwg', 23, 'g']),
list([3, 53, 13]), list(['225gg2g'])], dtype=object)