【问题标题】:How do I put objects at specific indices of a NumPy array without for loop?如何在没有 for 循环的情况下将对象放在 NumPy 数组的特定索引处?
【发布时间】:2018-04-13 01:36:21
【问题描述】:

如何在没有 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']

【问题讨论】:

  • this 本质上是你想要的吗?
  • @CoryKramer 这里的复杂之处在于np.ndarray 属于dtype 对象,并且可能基于花式索引的赋值l[[1,2]] = some_list 不会将some_list 视为标量值。当然,这都提出了一个问题,为什么 OP 使用 numpy.ndarray 开头
  • l[loc] = ['wgwg', 23, 'g'] 不起作用。它返回 array([[1, 3], 'wgwg', 23, [3, 53, 13], ['225gg2g']], dtype=object) 而不是 array([[1, 3], ['wgwg ', 23, 'g'], ['wgwg', 23, 'g'], [3, 53, 13], ['225gg2g']], dtype=object)
  • @gino 为什么你甚至在这里使用numpy?听起来您想要一个普通的list,但实际上听起来您需要重新考虑您完全组织数据的方式......

标签: python numpy


【解决方案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=>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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 2017-03-25
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多