簡體   English   中英

在Numpy中查找非零值/索引

[英]Finding Non-Zero Values/Indexes in Numpy

我有一個很大的numpy數組,其形狀為(12388,4)。 前兩個值是坐標,后兩個鍵值。 其中一些為零。 我想篩選整個數組,並找到其中后兩個值都不為零的所有索引。 我的代碼如下所示:

slice_index,_ = np.where((slice[:,2:4]!=0))
slice_nonzero_values = slice[slice_index]

所得數組slice_nonzero_values的形狀為(18550,4)。 因此,一定有問題,因為結果數組比原始數組大。 看着csv,我發現如果slice [:,2]和slice [:,3]都不為零,則np.where會多次返回相同的索引。 因此,我嘗試了includenp.unique:

slice_index,_ = np.where((slice[:,2:4]!=0))
slice_index_unique = np.unique(slice_index)
slice_nonzero_values = slice[slice_index_unique]

這導致形狀為(9669,4)。 看起來好多了。 但是,為了確保現在一切正常,我進行了以下循環:

    test = []
    test_index = []
    for index, i in enumerate(slice):
        if i[2]!=0 or i[3]!=0:
            test.append(i)
            test_index.append(index)
    test = np.array(test)
    test_index = np.array(test_index)

該循環導致形狀為(8881,4)的陣列測試。 現在,我完全困惑兩種方法中的哪一種是正確的。 根據循環的邏輯,測試數組必須是最嚴格的。 但是,這只是字面量的切片數組。 我不能離開循環。 總結一下:我想過濾切片數組,並獲取最后兩列中任一列均具有非零值的所有條目。 換句話說,如果兩個值(slice [:,2]和slice [:,3])均為零,則該行退出。 如果它們中只有一個為零,而另一個不是零,那很好。

這是切片數組的示例:

   array([[0.01032591, 0. , 0.               , 0.        ],
   [0.03256559, 0.00890732, 5.0000000e+00    , 0.        ],
   [0.0468626 , 0.01543951, 0.               , 0.        ],
   ...,
   [0.13899946, 0.8847985 , 0.               , 0.        ],
   [0.13899946, 0.8847985 , 4.0000000e+00    , 5.3900000e+02],
   [0.13899946, 0.8847985 , 0.               , 0.        ]], dtype=float32)

這是一個工作示例。 創建測試數據:

import numpy as np

X = np.random.rand(10,4)
X = np.vstack([X, np.zeros([2,4])])

>>> X
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
       [0.67277149, 0.01654403, 0.17710642, 0.54201684],
       # ...
       [0.        , 0.        , 0.        , 0.        ],
       [0.        , 0.        , 0.        , 0.        ]])

查找向量的最后兩個數字都不為零:

idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]

# alternatively, use np.any
idx = np.where(np.any(X[:,2:], axis=1))[0]

檢索過濾的向量:

X_none_zeros = X[idx]

>>> X_none_zeros
array([[0.09889965, 0.01169015, 0.30886119, 0.40204571],
       # ...
       [0.78279739, 0.84191242, 0.31685306, 0.54906034]])

>>> X_none_zeros.shape
(10, 4)

>>> X.shape
(12, 4)

說明:實際的代碼只有兩行:

# retrieve last 2 numbers for each vector in X
# and sum each vector horizontally, so you have 
# [s1, s2, s3, ...]
# use the condition to filter indexes
idx = np.where(np.sum(X[:,2:], axis=1) != 0)[0]
# retrieve matched vectors accordingly
X_none_zeros = X[idx]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM