Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xáo trộn (shuffle) các phần tử trong Series Python pandas

Giả sử bạn muốn xáo trộn ngẫu nhiên thứ tự các phần tử trong Series.

Cách 1: random.shuffle() (thay đổi tại chỗ)

import pandas as pd
import random as rand

data = pd.Series([1, 2, 3, 4, 5])
print("Series gốc:\n", data)

rand.shuffle(data)  # shuffle in-place trên mảng nền
print("\nSau shuffle:\n", data)

Cách 2: Thuật toán Fisher-Yates (thủ công)

import pandas as pd
import random

data = pd.Series([1, 2, 3, 4, 5])
print("Series gốc:\n", data)

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

print("\nSau shuffle (Fisher-Yates):\n", data)

Kết quả (mẫu - ngẫu nhiên)

Series gốc:
0    1
1    2
2    3
3    4
4    5
dtype: int64

Sau shuffle:
0    2
1    1
2    3
3    5
4    4
dtype: int64

Lưu ý:

  • random.shuffle() hoạt động trên mảng numpy nền của Series (in-place).
  • Cách 2 dùng iloc để hoán đổi an toàn với Series.
  • Để không thay đổi gốc: shuffled = data.sample(frac=1).reset_index(drop=True).