说我有以下数组d
:
>>> d = np.arange(25).reshape(5,5)
>>> d
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
我有向量l
告诉我d
中每行的长度:
>>> l = np.array([2,2,3,4,5])
>>> l
array([2, 2, 3, 4, 5])
如何将d
行中长度超过l
中指定的元素归零,以获得此结果:
>>> # zero out end of rows in `d`
>>> d
array([[ 0, 1, 0, 0, 0],
[ 5, 6, 0, 0, 0],
[10, 11, 12, 0, 0],
[15, 16, 17, 18, 0],
[20, 21, 22, 23, 24]])
这是针对张量流的,因此等效的tf会更好。谢谢!
答案 0 :(得分:1)
使用broadcasting
以矢量化方式创建尾随位置的蒙版,然后只需使用boolean-indexing
重置输入数组中的那些,就像这样 -
d[l[:,None] <= np.arange(d.shape[1])] = 0
l
中2D
到l[:,None]
tensorflow
的扩展名的等效值为:tf.expand_dims(l, 1)
或tf.expand_dims(l, -1)
。
示例运行 -
In [83]: d
Out[83]:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
In [84]: l = np.array([2,2,3,4,5])
# mask of trailing places
In [85]: l[:,None] <= np.arange(d.shape[1])
Out[85]:
array([[False, False, True, True, True],
[False, False, True, True, True],
[False, False, False, True, True],
[False, False, False, False, True],
[False, False, False, False, False]], dtype=bool)
In [86]: d[l[:,None] <= np.arange(d.shape[1])] = 0
In [87]: d
Out[87]:
array([[ 0, 1, 0, 0, 0],
[ 5, 6, 0, 0, 0],
[10, 11, 12, 0, 0],
[15, 16, 17, 18, 0],
[20, 21, 22, 23, 24]])