【发布时间】:2017-09-24 12:03:16
【问题描述】:
我看到一些我不理解的布尔索引行为,我希望在这里找到一些说明。
首先,这是我正在寻求的行为......
>>>
>>> a = np.zeros(10, dtype=np.ndarray)
>>> a
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=object)
>>> b = np.arange(10).reshape(2,5)
>>> b
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> a[5] = b
>>> a
array([0, 0, 0, 0, 0, array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]), 0,
0, 0, 0], dtype=object)
>>>
选择 ndarray 的 ndarray 的原因是因为我将追加存储在超级数组中的数组,它们的长度都不同。我为超级数组选择了类型 ndarray 而不是 list,这样我就可以访问所有 numpys 智能索引功能。
无论如何,如果我创建一个布尔索引器并使用它在位置 1 分配 b+5,它会做一些我没想到的事情
>>> indexer = np.zeros(10,dtype='bool')
>>> indexer
array([False, False, False, False, False, False, False, False, False, False], dtype=bool)
>>> indexer[1] = True
>>> indexer
array([False, True, False, False, False, False, False, False, False, False], dtype=bool)
>>> a[indexer] = b+5
>>> a
array([0, 5, 0, 0, 0, array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]), 0,
0, 0, 0], dtype=object)
>>>
谁能帮我理解发生了什么?我希望结果是
>>> a[1] = b+5
>>> a
array([0, array([[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]]), 0, 0,
0, array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]]), 0, 0, 0, 0], dtype=object)
>>>
最终的目标是在B中存储大量的“b”数组,并将它们分配给这样的a
>>> a[indexer] = B[indexer]
编辑:
根据下面的讨论找到了可能的解决方法。如果需要,我可以将数据包装在一个类中
>>>
>>> class myclass:
... def __init__(self):
... self.data = np.random.rand(1)
...
>>>
>>> b = myclass()
>>> b
<__main__.myclass object at 0x000002871A4AD198>
>>> b.data
array([ 0.40185378])
>>>
>>> a[indexer] = b
>>> a
array([None, <__main__.myclass object at 0x000002871A4AD198>, None, None,
None, None, None, None, None, None], dtype=object)
>>> a[1].data
array([ 0.40185378])
编辑: 这实际上失败了。索引时我无法为数据字段分配任何内容
【问题讨论】:
-
它没有:(它失败了......但感谢您提供的信息!我会在未来这样做
标签: numpy multidimensional-array indexing boolean