簡體   English   中英

從numpy數組中隨機選擇行

[英]Randomly selecting rows from numpy array

我想從一個numpy數組中隨機選擇行。 說我有這個數組-

A = [[1, 3, 0],
     [3, 2, 0],
     [0, 2, 1],
     [1, 1, 4],
     [3, 2, 2],
     [0, 1, 0],
     [1, 3, 1],
     [0, 4, 1],
     [2, 4, 2],
     [3, 3, 1]]

要隨機選擇說6行,我正在這樣做:

B = A[np.random.choice(A.shape[0], size=6, replace=False), :]

我想要另一個數組C ,其中的行未在B中選擇。

是否有一些內置方法可以執行此操作,或者我是否需要進行蠻力檢查B行與A行?

您可以使用布爾掩碼並從與您一樣長的整數數組中繪制隨機索引。 ~是元素形式的,不是:

idx = np.arange(A.shape[0])
mask = np.zeros_like(idx, dtype=bool)

selected = np.random.choice(idx, 6, replace=False)
mask[selected] = True

B = A[mask]
C = A[~mask]

您可以通過對隨機排列的行索引序列進行切片來對A進行任意數量的按行隨機分區:

ind = numpy.arange( A.shape[ 0 ] )
numpy.random.shuffle( ind )
B = A[ ind[ :6 ], : ]
C = A[ ind[ 6: ], : ]

如果不想更改每個子集中的行順序,可以對索引的每個切片進行排序:

B = A[ sorted( ind[ :6 ] ), : ]
C = A[ sorted( ind[ 6: ] ), : ]

(請注意,@ MaxNoe提供的解決方案還保留行順序。)

這為您提供了選擇的索引:

sel = np.random.choice(A.shape[0], size=6, replace=False)

和這個B

B = A[sel]

獲取所有未選擇的索引:

unsel = list(set(range(A.shape[0])) - set(sel))

並將它們用於C

C = A[unsel]

NumPy函數的變化

您可以使用以下方法來代替setlist

unsel2 = np.setdiff1d(np.arange(A.shape[0]), sel)

對於示例數組,純Python版本:

%%timeit
unsel1 = list(set(range(A.shape[0])) - set(sel)) 

100000 loops, best of 3: 8.42 µs per loop

比NumPy版本快:

%%timeit
unsel2 = np.setdiff1d(np.arange(A.shape[0]), sel)

10000 loops, best of 3: 77.5 µs per loop

對於較大的A ,NumPy版本更快:

A = np.random.random((int(1e4), 3))
sel = np.random.choice(A.shape[0], size=6, replace=False)


%%timeit
unsel1 = list(set(range(A.shape[0])) - set(sel))

1000 loops, best of 3: 1.4 ms per loop


%%timeit
unsel2 = np.setdiff1d(np.arange(A.shape[0]), sel)

1000 loops, best of 3: 315 µs per loop

暫無
暫無

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

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