重塑锯齿状数组并填充零 [英] Reshape jagged array and fill with zeros
本文介绍了重塑锯齿状数组并填充零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要完成的任务如下:考虑一个 1-D 数组 a
和一个索引数组部分
长度为 N
。示例:
The task I wish to accomplish is the following: Consider a 1-D array a
and an array of indices parts
of length N
. Example:
a = np.arange(9)
parts = np.array([4, 6, 9])
# a = array([0, 1, 2, 3, 4, 5, 6, 7, 8])
我想将 a
转换为形状为(N,<部分中最长分区的长度>)
,将 a
的值插入 indx
在 2-D 数组的每一行中,用零填充行的其余部分,例如:
I want to cast a
into a 2-D array of shape (N, <length of longest partition in parts>)
, inserting values of a
upto each index in indx
in each row of the 2-D array, filling the remaining part of the row with zeroes, like so:
array([[0, 1, 2, 3],
[4, 5, 0, 0],
[6, 7, 8, 0])
我不希望使用循环。
推荐答案
这里是一个 boolean-索引
-
def jagged_to_regular(a, parts):
lens = np.ediff1d(parts,to_begin=parts[0])
mask = lens[:,None]>np.arange(lens.max())
out = np.zeros(mask.shape, dtype=a.dtype)
out[mask] = a
return out
示例运行-
In [46]: a = np.arange(9)
...: parts = np.array([4, 6, 9])
In [47]: jagged_to_regular(a, parts)
Out[47]:
array([[0, 1, 2, 3],
[4, 5, 0, 0],
[6, 7, 8, 0]])
这篇关于重塑锯齿状数组并填充零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文