[英]Shuffle columns of an array with Numpy
假設我有一個維度為(n, m)
的數組r
。 我想洗牌該數組的列。
如果我使用numpy.random.shuffle(r)
它會numpy.random.shuffle(r)
線條。 我怎樣才能只洗牌? 使第一列成為第二列,第三列成為第一列,以此類推。
示例:
輸入:
array([[ 1, 20, 100],
[ 2, 31, 401],
[ 8, 11, 108]])
輸出:
array([[ 20, 1, 100],
[ 31, 2, 401],
[ 11, 8, 108]])
一種方法是打亂轉置數組:
np.random.shuffle(np.transpose(r))
另一種方法(參見 YXD 的回答https://stackoverflow.com/a/20546567/1787973 )是生成一個排列列表以按該順序檢索列:
r = r[:, np.random.permutation(r.shape[1])]
在性能方面,第二種方法更快。
對於通用軸,您可以遵循以下模式:
>>> import numpy as np
>>>
>>> a = np.array([[ 1, 20, 100, 4],
... [ 2, 31, 401, 5],
... [ 8, 11, 108, 6]])
>>>
>>> print a[:, np.random.permutation(a.shape[1])]
[[ 4 1 20 100]
[ 5 2 31 401]
[ 6 8 11 108]]
>>>
>>> print a[np.random.permutation(a.shape[0]), :]
[[ 1 20 100 4]
[ 2 31 401 5]
[ 8 11 108 6]]
>>>
因此,比您的答案更進一步:
編輯:我很容易弄錯這是如何工作的,所以我在每一步插入我對矩陣狀態的理解。
r == 1 2 3
4 5 6
6 7 8
r = np.transpose(r)
r == 1 4 6
2 5 7
3 6 8 # Columns are now rows
np.random.shuffle(r)
r == 2 5 7
3 6 8
1 4 6 # Columns-as-rows are shuffled
r = np.transpose(r)
r == 2 3 1
5 6 4
7 8 6 # Columns are columns again, shuffled.
然后將恢復到正確的形狀,重新排列列。
矩陣轉置的轉置 == 該矩陣,或者,[A^T]^T == A。因此,您需要在洗牌后進行第二次轉置(因為轉置不是洗牌)以使其再次處於適當的形狀。
編輯:OP 的答案跳過存儲換位,而是讓 shuffle 像 r 一樣對 r 進行操作。
一般來說,如果你想沿軸i
隨機播放一個 numpy 數組:
def shuffle(x, axis = 0):
n_axis = len(x.shape)
t = np.arange(n_axis)
t[0] = axis
t[axis] = 0
xt = np.transpose(x.copy(), t)
np.random.shuffle(xt)
shuffled_x = np.transpose(xt, t)
return shuffled_x
shuffle(array, axis=i)
>>> print(s0)
>>> [[0. 1. 0. 1.]
[0. 1. 0. 0.]
[0. 1. 0. 1.]
[0. 0. 0. 1.]]
>>> print(np.random.permutation(s0.T).T)
>>> [[1. 0. 1. 0.]
[0. 0. 1. 0.]
[1. 0. 1. 0.]
[1. 0. 0. 0.]]
np.random.permutation(),進行行排列。
還有另一種方法,它不使用換位並且顯然更快:
np.take(r, np.random.permutation(r.shape[1]), axis=1, out=r)
CPU 時間:用戶 1.14 毫秒,系統:1.03 毫秒,總計:2.17 毫秒。 掛牆時間:3.89 毫秒
其他答案中的方法: np.random.shuffle(rT)
CPU 時間:用戶 2.24 ms,系統:0 ns,總計:2.24 ms Wall time:5.08 ms
我使用r = np.arange(64*1000).reshape(64, 1000)
作為輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.