Skip to main content

Series와 DataFrame

Pandas의 모든 기능은 두 가지 핵심 데이터 구조 위에 구축되어 있습니다. Series는 인덱스가 있는 1차원 배열이고, DataFrame은 여러 Series가 열로 결합된 2차원 표입니다. 이 두 구조를 정확히 이해하는 것이 Pandas 활용의 출발점입니다.

학습 목표

  • Series와 DataFrame의 구조적 차이를 설명할 수 있다
  • 다양한 방법으로 Series와 DataFrame을 생성할 수 있다
  • 핵심 속성(shape, dtypes, index, columns)을 활용할 수 있다
  • head, tail, info, describe로 데이터를 빠르게 탐색할 수 있다

왜 중요한가

ML 프로젝트에서 데이터는 대부분 CSV, 데이터베이스, API에서 DataFrame 형태로 로드됩니다. DataFrame의 구조를 이해해야 피처(열)를 선택하고, 샘플(행)을 필터링하고, 데이터를 변환할 수 있습니다. sklearn의 많은 함수도 DataFrame을 입력으로 받습니다.

Series

Series는 인덱스(index)와 값(values)의 쌍으로 이루어진 1차원 구조입니다.
import pandas as pd
import numpy as np

# 리스트에서 생성
s = pd.Series([10, 20, 30, 40])
print(s)
# 0    10
# 1    20
# 2    30
# 3    40
# dtype: int64

# 인덱스 지정
s = pd.Series([85, 92, 78], index=['국어', '수학', '영어'])
print(s['수학'])  # 92

# 딕셔너리에서 생성
scores = pd.Series({'국어': 85, '수학': 92, '영어': 78})

# NumPy 배열에서 생성
arr = np.array([1.1, 2.2, 3.3])
s = pd.Series(arr, name='values')

Series 속성

s = pd.Series([10, 20, 30], index=['a', 'b', 'c'], name='data')

print(s.values)   # [10 20 30] — NumPy 배열
print(s.index)    # Index(['a', 'b', 'c'], dtype='object')
print(s.dtype)    # int64
print(s.name)     # 'data'
print(s.shape)    # (3,)
print(len(s))     # 3

DataFrame

DataFrame은 열(column)마다 서로 다른 dtype을 가질 수 있는 2차원 표 구조입니다.
# 딕셔너리에서 생성 (가장 일반적)
df = pd.DataFrame({
    '이름': ['김철수', '이영희', '박민수'],
    '나이': [25, 30, 28],
    '점수': [85.5, 92.3, 78.1]
})
print(df)
#     이름  나이   점수
# 0  김철수  25  85.5
# 1  이영희  30  92.3
# 2  박민수  28  78.1

# 리스트의 리스트에서 생성
df2 = pd.DataFrame(
    [[1, 'A', True],
     [2, 'B', False],
     [3, 'C', True]],
    columns=['번호', '등급', '활성']
)

# NumPy 배열에서 생성
arr = np.random.randn(5, 3)
df3 = pd.DataFrame(arr, columns=['feature_1', 'feature_2', 'feature_3'])

DataFrame 속성

df = pd.DataFrame({
    '이름': ['김철수', '이영희', '박민수'],
    '나이': [25, 30, 28],
    '점수': [85.5, 92.3, 78.1]
})

print(df.shape)      # (3, 3) — 3행 3열
print(df.columns)    # Index(['이름', '나이', '점수'], dtype='object')
print(df.index)      # RangeIndex(start=0, stop=3, step=1)
print(df.dtypes)
# 이름     object
# 나이      int64
# 점수    float64
print(df.values)     # 2D NumPy 배열

데이터 빠르게 탐색하기

# 예시 데이터 생성
np.random.seed(42)
df = pd.DataFrame({
    'id': range(1, 101),
    'age': np.random.randint(18, 65, 100),
    'salary': np.random.normal(50000, 15000, 100).round(0),
    'department': np.random.choice(['영업', '개발', '마케팅', '인사'], 100)
})

# 상위/하위 행 확인
print(df.head())       # 상위 5행
print(df.tail(3))      # 하위 3행

# 데이터 요약 정보
print(df.info())
# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 100 entries, 0 to 99
# Data columns (total 4 columns):
#  #   Column      Non-Null Count  Dtype
# ---  ------      --------------  -----
#  0   id          100 non-null    int64
#  1   age         100 non-null    int64
#  2   salary      100 non-null    float64
#  3   department  100 non-null    object

# 기술통계 (수치형 열만)
print(df.describe())
#                id        age        salary
# count  100.00000  100.00000    100.000000
# mean    50.50000   40.57000  49652.300000
# std     29.01149   13.60000  14287.530000
# ...

# 범주형 열 기술통계
print(df.describe(include='object'))
#        department
# count         100
# unique          4
# top            영업
# freq           30

# 고유값 확인
print(df['department'].value_counts())
# 영업      30
# 개발      28
# 마케팅    22
# 인사      20

print(df['department'].nunique())  # 4

열 선택과 추가

# 단일 열 선택 → Series
ages = df['age']
print(type(ages))  # <class 'pandas.core.series.Series'>

# 여러 열 선택 → DataFrame
subset = df[['age', 'salary']]
print(type(subset))  # <class 'pandas.core.frame.DataFrame'>

# 새 열 추가
df['bonus'] = df['salary'] * 0.1
df['age_group'] = pd.cut(df['age'], bins=[18, 30, 45, 65],
                          labels=['청년', '중년', '장년'])

# 열 삭제
df = df.drop(columns=['bonus'])
# 또는
# del df['bonus']

AI/ML에서의 활용

  • 피처 행렬: DataFrame의 수치형 열을 df[feature_cols].values로 추출하여 sklearn에 전달합니다
  • 타겟 변수: 예측 대상 열을 Series로 분리합니다: y = df['target']
  • 데이터 탐색: info(), describe(), value_counts()로 데이터 품질을 빠르게 파악합니다
  • 메타데이터: dtypesshape으로 피처의 타입과 데이터셋 크기를 확인합니다
DataFrame은 같은 인덱스를 공유하는 여러 Series의 모음입니다. df['column_name']으로 접근하면 해당 열의 Series를 반환합니다. Series는 DataFrame의 구성 요소이면서 독립적으로도 사용됩니다.
object는 Pandas에서 문자열이나 혼합 타입 데이터에 사용되는 dtype입니다. 문자열 전용 dtype인 StringDtype (pd.StringDtype())도 있지만, 아직은 object가 기본값입니다.

체크리스트

  • Series와 DataFrame의 구조적 차이를 설명할 수 있다
  • 딕셔너리, 리스트, NumPy 배열에서 DataFrame을 생성할 수 있다
  • shape, dtypes, columns, index 속성을 활용할 수 있다
  • head(), info(), describe()로 데이터를 빠르게 파악할 수 있다
  • 열의 선택, 추가, 삭제를 수행할 수 있다

다음 문서