編寫一個 Python 程式,對給定序列中的所有元素進行隨機排序。
假設您有一個數據框,並且需要對其中一個序列的所有資料進行隨機排序,
The original series is 0 1 1 2 2 3 3 4 4 5 dtype: int64 The shuffled series is : 0 2 1 1 2 3 3 5 4 4 dtype: int64
方案 1
定義一個序列。
應用隨機排序方法,該方法將序列資料作為引數並對其進行排序。
data = pd.Series([1,2,3,4,5]) print(data) rand.shuffle(data)
示例
讓我們看看下面的程式碼來更好地理解 -
import pandas as pd
import random as rand
data = pd.Series([1,2,3,4,5])
print("original series is\n",data)
rand.shuffle(data)
print("shuffles series is\n",data)輸出
original series is 0 1 1 2 2 3 3 4 4 5 dtype: int64 shuffles series is 0 2 1 3 2 1 3 5 4 4 dtype: int64
方案 2
定義一個序列。
建立一個 for 迴圈來訪問序列資料並在 j 變數中生成隨機索引。定義如下,
for i in range(len(data)-1, 0, -1): j = random.randint(0, i + 1)
將 data[i] 與隨機索引位置處的元素交換,
data[i], data[j] = data[j], data[i]
示例
讓我們看看下面的程式碼來更好地理解 -
import pandas as pd
import random
data = pd.Series([1,2,3,4,5])
print ("The original series is \n", data)
for i in range(len(data)-1, 0, -1):
j = random.randint(0, i + 1)
data[i], data[j] = data[j], data[i]
print ("The shuffled series is : \n ", data)輸出
The original series is 0 1 1 2 2 3 3 4 4 5 dtype: int64 The shuffled series is : 0 2 1 1 2 3 3 5 4 4 dtype: int64
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP