“Python” Sort Array by Designated Order. Shuffle is also Possible.

AI
higashi
higashi

Hi, I’m higashi.

 

This page introduce how to sort array by designated order.

Of course by using this method, shuffle is also possible.

It is necessary skill to make teacher data for AI.

 

So, let’s get started!!

 

Sponsored Links

How to Sort Array by Designated Order.

The method of sort array by designated order is below.

after_sort_array=before_sort_array [ order_list ] 

 

I think it is difficult to understand only this.

I show the sample at next section.

 

Sponsored Links

Sample Code of Sorting Array

So, let’s use the skill shown above.

import numpy as np
a=np.array([[1,2,3],
            [4,5,6],
            [7,8,9]])
b=[2,1,0]
c=a[b]
print(c)

a : befor sort array

b : order list

c : after sort array

Please check against the program and below tips.

after_sort_array=before_sort_array [ order_list ] 

By conduction this program, below result is shown.

並び替えた後の配列を出力した結果

It is likely sorted by designated order.

Sponsored Links

How to Sort Array Randomly

By applying the above skill, if only we have the order list that is made randomly,  we can sort array randomly.

 

So at first, let’s make random order list.

The method is shown below.

import random
data_number=len(befor_sort_array)
shuffle_list=random.sample(range(0,data_number),data_number)

 

The sorting method by using this ‘shuffle list’ is shown below.

after_sort_array=before_sort_array [ shuffle_list ] 

It is completely same with before.

 

Sponsored Links

Sample Code of Sorting Array Randomly

I demonstrate the array shuffle by using sample array.

The sample code is below.

import numpy as np
import random
a=np.array([[1,2,3],
            [4,5,6],
            [7,8,9],
            [-1,-2,-3],
            [-4,-5,-6],
            [-7,-8,-9]])
shuffle_list=random.sample(range(0,len(a)),len(a))
print(shuffle_list)
c=a[shuffle_list]
print(c)

By conducting the code, below result is displayed.

This is result of shuffle list.

シャッフル用のリストを作成した結果

And this is result of array after shuffle.

シャッフルした後の配列を出力した結果

It is likely shuffled by shuffle list with no problem.

 

Please confirm that the result is changed every program conduct.

 

That’s all. Thank you!!

コメント