我有一個按行排序的廣播陣列和一個屏蔽陣列。我想得到每行的最后n 個元素(或前n個元素)是True即:
a = np.array([[0.00298, 0.00455, 0.00767, 0.00939, 0.01104, 0.02351, 0.03370],
[0.00298, 0.00455, 0.00767, 0.00939, 0.01104, 0.02351, 0.03370],
[0.00298, 0.00455, 0.00767, 0.00939, 0.01104, 0.02351, 0.03370]])
mask = np.array([[1, 0, 0, 1, 1, 0, 1], [0, 1, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 0]], dtype=bool)
# a[mask] --> [0.00298 0.00939 0.01104 0.0337 0.00455 0.02351 0.0337 0.00767 0.00939]
# needed last two --> [[0.01104 0.0337 ] [0.02351 0.0337 ] [0.00767 0.00939]]
# needed first two --> [[0.00298 0.00939] [0.00455 0.02351] [0.00767 0.00939]]
我們是否必須拆分陣列(使用np.cumsum(np.sum(mask, axis=1)))、pad 和...?僅使用 NumPy
的最佳方法是什么?
uj5u.com熱心網友回復:
使用 numpy 獲取第一個 n True:
n=2
a[(np.cumsum(mask, axis=1)<=n)&mask].reshape(-1,n)
輸出:
array([[0.00298, 0.00939],
[0.00455, 0.02351],
[0.00767, 0.00939]])
最后 n:
n=2
a[(np.cumsum(mask[:,::-1], axis=1)<=n)[:,::-1]&mask].reshape(-1,n)
輸出:
array([[0.01104, 0.0337 ],
[0.02351, 0.0337 ],
[0.00767, 0.00939]])
注意。每行必須至少有 n 個 True 才能獲得正確的最終形狀
uj5u.com熱心網友回復:
您可以通過將陣列相乘并使用帶有切片的串列推導來分別獲取第一個或最后兩個元素來做到這一點:
# First two:
[[i for i in j if i][:2] for j in a*mask]
# Last two:
[[i for i in j if i][-2:] for j in a*mask]
輸出:
[[0.00298, 0.00939], [0.00455, 0.02351], [0.00767, 0.00939]]
[[0.01104, 0.0337], [0.02351, 0.0337], [0.00767, 0.00939]]
編輯,僅使用 numpy 函式:
# First two:
np.apply_along_axis(lambda x: x[np.flatnonzero(x)[:2]], axis=1, arr=mask*a)
# Last two:
np.apply_along_axis(lambda x: x[np.flatnonzero(x)[-2:]], axis=1, arr=mask*a)
輸出:
array([[0.00298, 0.00939], [0.00455, 0.02351], [0.00767, 0.00939]])
array([[0.01104, 0.0337 ], [0.02351, 0.0337 ], [0.00767, 0.00939]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484215.html
