我想知道提取n二維陣列中每列第一個非零值的索引的最快方法。
例如,使用以下陣列:
arr = [
[4, 0, 0, 0],
[0, 0, 0, 0],
[0, 4, 0, 0],
[2, 0, 9, 0],
[6, 0, 0, 0],
[0, 7, 0, 0],
[3, 0, 0, 0],
[1, 2, 0, 0],
有了n=2我就會有[0, 0, 1, 1, 2]xs 和[0, 3, 2, 5, 3]ys。第一列和第二列中有 2 個值,第三列中有 1 個值。
以下是目前的做法:
x = []
y = []
n = 3
for i, c in enumerate(arr.T):
a = c.nonzero()[0][:n]
if len(a):
x.extend([i]*len(a))
y.extend(a)
在實踐中,我有 size 的陣列(405, 256)。
有沒有辦法讓它更快?
uj5u.com熱心網友回復:
這是一種方法,盡管由于使用了很多函式而令人困惑,但它不需要對陣列進行排序(只需要線性掃描即可獲得非空值):
n = 2
# Get indices with non null values, columns indices first
nnull = np.stack(np.where(arr.T != 0))
# split indices by unique value of column
cols_ids= np.array_split(range(len(nnull[0])), np.where(np.diff(nnull[0]) > 0)[0] 1 )
# Take n in each (max) and concatenate the whole
np.concatenate([nnull[:, u[:n]] for u in cols_ids], axis = 1)
輸出:
array([[0, 0, 1, 1, 2],
[0, 3, 2, 5, 3]], dtype=int64)
uj5u.com熱心網友回復:
這是使用的一種方法argsort,但它給出了不同的順序:
n = 2
m = arr!=0
# non-zero values first
idx = np.argsort(~m, axis=0)
# get first 2 and ensure non-zero
m2 = np.take_along_axis(m, idx, axis=0)[:n]
y,x = np.where(m2)
# slice
x, idx[y,x]
# (array([0, 1, 2, 0, 1]), array([0, 2, 3, 3, 5]))
uj5u.com熱心網友回復:
對轉置非零的行結果使用錯位比較:
>>> n = 2
>>> i, j = arr.T.nonzero()
>>> mask = np.concatenate([[True] * n, i[n:] != i[:-n]])
>>> i[mask], j[mask]
(array([0, 0, 1, 1, 2], dtype=int64), array([0, 3, 2, 5, 3], dtype=int64))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/511867.html
上一篇:如何根據PythonPandas中兩列中的值聚合DataFrame并洗掉重復項?
下一篇:如果N在預定范圍內,則執行操作
