如何在没有for循环的情况下将对象放在NumPy数组的特定索引处?

时间:2017-10-31 19:09:49

标签: python numpy

如果没有for循环,我该如何进行以下操作?

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']

1 个答案:

答案 0 :(得分:1)

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

它正在尝试将3个项目列表(转换为数组?)广播到2个项目的插槽中。

我们可以将列表包装在另一个列表中,因此它现在是单个项目列表:

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)

好像我们一个接一个地复制它:

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)

解决这个3 =&gt; 2映射问题并不容易。

但为什么你需要这样做?它看起来很可疑。

修改

它的工作原理我首先创建一个0d对象数组:

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)