데이터셋 처리(Process)

데이터셋 처리(Process)

Datasets는 데이터셋의 구조·내용을 수정하는 다양한 도구를 제공해요. 데이터 정리, 컬럼 추가, 특징·형식 변환 등에 쓰여요. 이 문서에서는 행 재배치·분할, 컬럼 이름 변경·삭제, 각 예제에 처리 함수 적용, 데이터셋 결합, 포맷 변환, 저장·내보내기를 다뤄요.

중요한 전제가 하나 있어요. 이 가이드의 모든 처리 메서드는 새로운 Dataset 객체를 반환하며 in-place 수정이 아니에요. 그러니 기존 데이터셋을 덮어쓰지 않게 조심해야 해요.

출처: https://huggingface.co/docs/datasets/en/process

정렬·셔플·선택·분할·샤딩

  • sort(): 값을 기준으로 정렬해요. 정렬할 컬럼은 NumPy 호환 값이어야 해요.
  • shuffle(seed=...): 행을 무작위로 섞어요.
  • select(indexes): 인덱스 목록으로 행을 골라요.
  • filter(cond): 조건을 만족하는 행만 남겨요. with_indices=True로 인덱스 기반 필터도 가능해요.
  • train_test_split(test_size=...): train/test 분할을 만들거나 비율을 조정해요.
  • shard(num_shards, index): 큰 데이터셋을 여러 조각으로 나눠요.
from datasets import load_dataset

dataset = load_dataset("nyu-mll/glue", "mrpc", split="train")
sorted_dataset = dataset.sort("label")
shuffled_dataset = sorted_dataset.shuffle(seed=42)
even_dataset = dataset.filter(lambda example, idx: idx % 2 == 0, with_indices=True)

셔플이나 비연속 필터는 indices 매핑을 만들고, 이러면 속도가 최대 10배 느려질 수 있어요. flatten_indices()로 되돌리면 속도를 복원할 수 있어요.

컬럼 조작

  • rename_column(old, new): 컬럼 이름 변경.
  • remove_columns(names) / select_columns(names): 컬럼 제거·선택.
  • cast(features): 컬럼의 특징(타입) 변환(예: ClassLabel, Value).
dataset = dataset.rename_column("sentence1", "sentenceA")
dataset = dataset.remove_columns("label")

예제 단위 처리

map()로 각 예제(또는 배치)에 처리 함수를 적용할 수 있어요. 한 줄에도 성능이 신경 쓰인다면 batched=True·num_proc을 써서 배치·병렬 처리를 활용해요.

def add_length(example):
    example["length"] = len(example["sentence1"])
    return example

dataset = dataset.map(add_length)

저장·내보내기

  • Hub에 업로드: push_to_hub("username/my_dataset", num_proc=8).
  • 로컬 Arrow 저장: save_to_disk() / load_from_disk(). 재로드가 빨라 로컬·임시 캐시에 좋아요.
  • 내보내기: to_csv(), to_json(), to_parquet(), to_sql(), to_pandas() 등.
  • hf:// 경로: Hub 데이터셋 저장소나 Storage Bucket으로 직접 내보낼 수 있어요.
encoded_dataset.push_to_hub("username/my_dataset")
encoded_dataset.save_to_disk("path/of/my/dataset/directory")
encoded_dataset.to_csv("path/of/my/dataset.csv")

더 알아보기