python - 使用 Pythonic 向量化代码在 2D numpy 数组中索引不同大小的范围

标签 python numpy numpy-slicing

我有一个 numpy 二维数组,我想根据列索引选择这个数组的不同大小范围。这是输入数组 a = np.reshape(np.array(range(15)), (5, 3))例子

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]]
然后,列出 b = [4,3,1]确定每个列切片的不同范围大小,以便我们获得数组
[0 3 6 9]
[1 4 7]
[2]
我们可以连接和展平以获得最终所需的输出
[0 3 6 9 1 4 7 2]
目前,要执行此任务,我正在使用以下代码
slices = []
for i in range(a.shape[1]):
    slices.append(a[:b[i],i])

c = np.concatenate(slices)
并且,如果可能,我想将其转换为 pythonic 格式。
奖金:同样的问题,但现在考虑到 b确定行切片而不是列。

最佳答案

我们可以使用 broadcasting生成适当的掩码,然后 masking做这项工作 -

In [150]: a
Out[150]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])

In [151]: b
Out[151]: [4, 3, 1]

In [152]: mask = np.arange(len(a))[:,None] < b

In [153]: a.T[mask.T]
Out[153]: array([0, 3, 6, 9, 1, 4, 7, 2])
另一种屏蔽方法是-
In [156]: a.T[np.greater.outer(b, np.arange(len(a)))]
Out[156]: array([0, 3, 6, 9, 1, 4, 7, 2])
奖励:每行切片
如果我们需要根据块大小对每行进行切片,我们需要修改一些东西 -
In [51]: a
Out[51]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

# slice lengths per row
In [52]: b
Out[52]: [4, 3, 1]

# Usual loop based solution :
In [53]: np.concatenate([a[i,:b_i] for i,b_i in enumerate(b)])
Out[53]: array([ 0,  1,  2,  3,  5,  6,  7, 10])

# Vectorized mask based solution :
In [54]: a[np.greater.outer(b, np.arange(a.shape[1]))]
Out[54]: array([ 0,  1,  2,  3,  5,  6,  7, 10])

关于python - 使用 Pythonic 向量化代码在 2D numpy 数组中索引不同大小的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63380108/

相关文章:

python - Pandas - 根据列值对输入值进行排名

python - Numpy 类型错误

python - MySQLdb 查询包含 NULL 到 Numpy 数组

python - NumPy:为什么需要显式复制一个值?

python - 用链式掩码替换 numpy 数组元素

python - 以最快的方式确定 Python 数组中每组重复值的索引

python - 如何在 Alteryx 或 Python 中将日期转换为一周中的第 n 天?

python - 用换行符写文本文件

numpy - 在 numpy/pytorch 中使用 bool 数组或索引数组进行索引更快吗?

python - 为什么 a[1 :-1:-1] with a=[1, 2,3] 返回 []?