Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permute within a row in python

Tags:

python

numpy

I have two arrays that are paired meaning that element 1 in both arrays needs to have the same index. I want to permute these elements. Currently, I tried np.random.permutation but that does not seem to get the right answer.

For example, if the two arrays are [1,2,3] and [4,5,6], one possible permutation would be [4,2,3] and [1,5,6].

like image 613
STR Avatar asked Jan 30 '26 08:01

STR


1 Answers

You can stack your arrays and choose a random column for each row using choice.

Setup

a = np.array([1,2,3])
b = np.array([4,5,6])    
v = np.column_stack((a,b))

# array([[1, 4],
#        [2, 5],
#        [3, 6]])

np.random.seed(1)
choices = np.random.choice(v.shape[1], v.shape[0])
# array([1, 1, 0])

Finally, to index:

v[np.arange(v.shape[0]), choices]

array([4, 5, 3])
like image 82
user3483203 Avatar answered Jan 31 '26 21:01

user3483203