데이터프레임이 하나 있고, 그 안의 시리즈(Series)에 담긴 모든 데이터를 무작위로 섞었을 때 결과가 다음과 같다고 가정해 보겠습니다.
원본 시리즈 0 1 1 2 2 3 3 4 4 5 dtype: int64 섞인 후의 시리즈 : 0 2 1 1 2 3 3 5 4 4 dtype: int64
방법 1 — random.shuffle() 함수 사용
시리즈를 정의합니다.
random.shuffle() 메서드에 시리즈 데이터를 인수로 전달하면 해당 시리즈가 제자리(in-place)에서 무작위로 섞입니다.
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("원본 시리즈:\n", data)
rand.shuffle(data)
print("섞인 후의 시리즈:\n", data)
출력
원본 시리즈: 0 1 1 2 2 3 3 4 4 5 dtype: int64 섞인 후의 시리즈: 0 2 1 3 2 1 3 5 4 4 dtype: int64
방법 2 — Fisher-Yates 알고리즘 직접 구현
시리즈를 정의합니다.
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("원본 시리즈:\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("섞인 후의 시리즈:\n", data)
출력
원본 시리즈: 0 1 1 2 2 3 3 4 4 5 dtype: int64 섞인 후의 시리즈: 0 2 1 1 2 3 3 5 4 4 dtype: int64
보너스: pandas의 sample() 메서드 활용
판다스에서는 별도의 반복문 없이 sample() 메서드 한 줄로 시리즈 전체를 섞을 수도 있습니다. frac=1은 전체 데이터를 반환하되 순서를 무작위로 변경하라는 의미이며, reset_index(drop=True)를 함께 사용하면 인덱스도 깔끔하게 초기화됩니다.
shuffled = data.sample(frac=1).reset_index(drop=True)