สมมติว่าคุณมี Series และต้องการสลับลำดับข้อมูลแบบสุ่ม
วิธีที่ 1: ใช้ random.shuffle()
- สร้าง Series
- ใช้
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)
- สร้าง Series
- วนลูปจากท้ายมาหน้า สลับกับตำแหน่งสุ่ม
ตัวอย่าง
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 ใหม่ที่สลับแล้ว