기계는 거짓말하지 않는다

Python Pandas 조건에 맞는 데이터 일정 비율 추출 본문

Python

Python Pandas 조건에 맞는 데이터 일정 비율 추출

KillinTime 2023. 5. 6. 00:01

DataFrame에서 조건을 만족하는 행 중 일정 비율 추출하는 예시이다.

 

custom_data.csv

count가 50보다 작은 행들 중 40% 데이터만 랜덤으로 추출하려면 아래와 같이 할 수 있다.

import pandas as pd
import random

df = pd.read_csv("custom_data.csv", encoding="utf-8")

# count가 50보다 큰 행의 인덱스
rows_to_select = df[df["count"] < 50].index
print(rows_to_select)
print(df.iloc[rows_to_select])

print("-" * 50)

# 조건에 맞는 인덱스 중 랜덤하게 40% 추출
rows_to_select = list(rows_to_select)
random.seed(42)
random.shuffle(rows_to_select)
print(rows_to_select)

select_ratio = 0.4

rows_to_select = rows_to_select[:int(select_ratio * len(rows_to_select))]
selected_df = df.iloc[rows_to_select]
print(selected_df)

실행 결과

Comments