머신러닝과 기술적 분석

[python] 순서를 유지하면서 random sampling 하기 본문

python

[python] 순서를 유지하면서 random sampling 하기

BetterToday 2022. 9. 17. 16:18
728x90

 

그냥 random.sample() 하면 기존의 순서유지가 안된다. 간단하게 List의 index를 random sample하면 됨.

 

import numpy as np
import random


input_items = [1, 2, 5, 10, 6]

# 1. 순서 관계없이 샘플링
sample_items = random.sample(input_items, 2)
print(sample_items)
# [6, 5]

# 2. 순서를 유지
sample_idxes = random.sample(range(len(input_items)), 2)
sample_idxes.sort()
sample_items = np.array(input_items)[sample_idxes].tolist()
print(sample_items)
# [2, 5]
728x90
반응형
Comments