Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python สลับลำดับข้อมูลใน Series แบบสุ่ม (Shuffle)

สมมติว่าคุณมี Series และต้องการสลับลำดับข้อมูลแบบสุ่ม

วิธีที่ 1: ใช้ random.shuffle()

  1. สร้าง Series
  2. ใช้ random.shuffle(data) สลับแบบ in-place

ตัวอย่าง

import pandas as pd
import random as rand

data = pd.Series([1, 2, 3, 4, 5])
print("Series ต้นฉบับ:\n", data)

rand.shuffle(data)
print("\nSeries หลัง shuffle:")
print(data)

วิธีที่ 2: ใช้ Fisher-Yates shuffle algorithm (manual)

  1. สร้าง Series
  2. วนลูปจากท้ายมาหน้า สลับกับตำแหน่งสุ่ม

ตัวอย่าง

import pandas as pd
import random

data = pd.Series([1, 2, 3, 4, 5])
print("Series ต้นฉบับ:\n", data)

for i in range(len(data) - 1, 0, -1):
    j = random.randint(0, i)
    data[i], data[j] = data[j], data[i]

print("\nSeries หลัง shuffle (manual):")
print(data)

ผลลัพธ์ตัวอย่าง (สุ่มทุกครั้ง)

Series ต้นฉบับ:
0    1
1    2
2    3
3    4
4    5
dtype: int64

Series หลัง shuffle:
0    2
1    1
2    3
3    5
4    4
dtype: int64

คำอธิบาย:

  • random.shuffle() ทำงาน in-place บน list-like object (Series ทำงานได้เพราะเป็น mutable sequence)
  • วิธีที่ 2 เป็นการ implement Fisher-Yates shuffle เอง ให้การกระจายสุ่มที่ดี
  • ใน pandas ใหม่ แนะนำให้ใช้ df.sample(frac=1) หรือ series.sample(frac=1) แทน ซึ่งคืนค่า Series ใหม่ที่สลับแล้ว