简体   繁体   中英

Numpy apply the same random permutation to two different ndarray with the same shape

Suppose I have two NumPy arrays, say, each of shape (N,1). The first array is an Array called Age and the second called income. Suppose These attributes are samples of different people, so the ith index refers to the ith person in the sample and by knowing i I can retrieve both his age and income. Now suppose I want to permutate both arrays randomly (or deterministically) so that both undergo the same permutation? I mean, After the permutation, the index j of both arrays refer to the attribute of the same person? I know one way of doing this is defining objects of a person with two attributes: age and income , but I want the Numpy way of doing so. Thanks.

You could first create a permutation of indices, then access both arrays with the same permutation of indices. This could be done using numpy.random.permutation , for instance.

Example:

>>> age = np.random.randint(0,100,10)
>>> income = np.random.randint(0,10000,10)
>>> age
array([38,  4, 70, 16,  8, 29,  1, 41, 54, 60])
>>> income
array([4797, 5884, 8005, 5696, 7577, 6386, 3314, 3574, 5422,  409])
>>> permutation_indices = np.random.permutation(10)
>>> permutation_indices
array([9, 1, 8, 0, 7, 3, 2, 6, 5, 4])
>>> age[permutation_indices]
array([60,  4, 54, 38, 41, 16, 70,  1, 29,  8])
>>> income[permutation_indices]
array([ 409, 5884, 5422, 4797, 3574, 5696, 8005, 3314, 6386, 7577])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM