簡體   English   中英

從numpy數組中刪除選擇索引處的行

[英]Delete rows at select indexes from a numpy array

在我的數據集中,我已經接近200行,但是為了進行最少的工作,例如,讓我們假設以下數組:

arr = np.array([[1,2,3,4], [5,6,7,8], 
               [9,10,11,12], [13,14,15,16], 
               [17,18,19,20], [21,22,23,24]])

我可以對以下3行進行隨機抽樣:

indexes = np.random.choice(np.arange(arr.shape[0]), int(arr.shape[0]/2), replace=False)

使用這些索引,我可以如下選擇測試用例:

testing = arr[indexes]

我想刪除這些索引處的行,並且可以將其余元素用於我的訓練集。

這里的帖子中看來, training = np.delete(arr, indexes)應該應該這樣做。 但是我得到了一維數組。

我在這里也使用training = arr[indexes.astype(np.bool)]嘗試了建議但沒有給出training = arr[indexes.astype(np.bool)]分隔。 我在訓練和測試集中都得到了元素[5,6,7,8]。

training = arr[indexes.astype(np.bool)]

testing
Out[101]: 
array([[13, 14, 15, 16],
       [ 5,  6,  7,  8],
       [17, 18, 19, 20]])

training
Out[102]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

知道我在做什么錯嗎? 謝謝。

要從numpy數組中刪除索引行:

arr = np.delete(arr, indexes, axis=0)

一種方法是使用np.setdiff1d獲取其余的行索引,然后使用這些行索引獲取所需的輸出-

out = arr[np.setdiff1d(np.arange(arr.shape[0]), indexes)]

或使用np.in1d來利用boolean indexing -

out = arr[~np.in1d(np.arange(arr.shape[0]), indexes)]

暫無
暫無

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

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