gpt4 book ai didi

python - numpy 数组的时髦行为

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:50 25 4
gpt4 key购买 nike

我希望有人能向我解释我用 numpy 数组观察到的以下行为:

>>> import numpy as np
>>> data_block=np.zeros((26,480,1000))
>>> indices=np.arange(1000)
>>> indices.shape
(1000,)
>>> data_block[0,:,:].shape
(480, 1000) #fine and dandy
>>> data_block[0,:,indices].shape
(1000, 480) #what happened???? why the transpose????
>>> ind_slice=np.arange(300) # this is more what I really want.
>>> data_block[0,:,ind_slice].shape
(300, 480) # transpose again! arghhh!

我不明白这种转置行为,这对我想做的事情来说很不方便。谁能给我解释一下?获取 data_block 子集的替代方法将是一个很好的奖励。

最佳答案

您可以通过这种方式实现您想要的结果:

>>> data_block[0,:,:][:,ind_slice].shape
(480L, 300L)

我承认我并不完全了解 numpy 索引的工作原理,但是 the documentation似乎暗示了你遇到的麻烦:

Basic slicing with more than one non-: entry in the slicing tuple, acts like repeated application of slicing using a single non-: entry, where the non-: entries are successively taken (with all other non-: entries replaced by :). Thus, x[ind1,...,ind2,:] acts like x[ind1][...,ind2,:] under basic slicing.

Warning: The above is not true for advanced slicing.

和。 . .

Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool).

因此,您通过使用 ind_slice 数组而不是常规切片进行索引来触发该行为。

文档本身说这种索引“可能有点难以理解”,所以我们都遇到这个问题不足为奇:-)。

关于python - numpy 数组的时髦行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com