본문으로 건너뛰기
김신건의 로그

[Pandas] 개요

· 수정 · 📖 약 2분 · 790자/단어 #python #pandas #data-analysis #data-science
pandas, 판다스, pandas overview, Python pandas, pandas 라이브러리

정의

pandas 는 Python 의 데이터 분석/조작 라이브러리. 두 가지 핵심 자료형을 중심으로 동작한다.

NumPy 의 ndarray 위에 구축되어 빠른 수치 연산과 SQL/Excel 스타일의 직관적 조작을 결합. 데이터 분석, ETL, 머신러닝 전처리의 사실상 표준.

빠르게 보기

python
import pandas as pd

df = pd.DataFrame({
  'name': ['Alice', 'Bob', 'Charlie'],
  'age': [30, 25, 35],
  'city': ['Seoul', 'Busan', 'Seoul'],
})
print(df)
print(df.shape, df.dtypes.tolist())
결과
      name  age   city
0    Alice   30  Seoul
1      Bob   25  Busan
2  Charlie   35  Seoul
(3, 3) [dtype('O'), dtype('int64'), dtype('O')]

테이블 형태로 보면:

nameagecity
0Alice30Seoul
1Bob25Busan
2Charlie35Seoul

역사와 배경

연도이정표
2008Wes McKinney, AQR Capital Management 에서 개발 시작
2009오픈소스 공개
2012Python for Data Analysis 초판, 생태계 폭발적 성장
2020pandas 1.0 - nullable dtypes 도입
2023pandas 2.0 - Copy-on-Write(CoW), PyArrow 백엔드 기본화
2024pandas 2.2 - Arrow-backed strings, Copy-on-Write 완전 기본화

pandas 생태계 구조

flowchart TD
    subgraph "하위 계층"
        NP["NumPy (ndarray)"]
        PA["PyArrow (Apache Arrow)"]
    end

    subgraph "pandas 핵심"
        SR["Series (1D)"]
        DF["DataFrame (2D)"]
        IX["Index"]
    end

    subgraph "연계 라이브러리"
        MPL["Matplotlib / Seaborn"]
        SK["scikit-learn"]
        SP["SciPy"]
        PL["Polars"]
    end

    NP --> SR
    NP --> DF
    PA --> SR
    PA --> DF
    SR --> DF
    IX --> SR
    IX --> DF
    DF --> MPL
    DF --> SK
    DF --> SP
    DF -.->|"Arrow 호환"| PL

NumPy / PyArrow 와의 관계

NumPy 기반

전통적으로 pandas Series/DataFrame 의 내부는 NumPy ndarray. 빠른 수치 연산이 가능하지만 문자열/nullable 타입에는 약했다.

import numpy as np, pandas as pd

arr = np.array([1, 2, 3])
s = pd.Series(arr)          # NumPy array 위에 index 추가
s.values                     # 다시 numpy array 로

PyArrow 백엔드 (pandas 2.0+)

# Arrow 기반 dtype
s = pd.Series(['a', 'b', 'c'], dtype='string[pyarrow]')
df = pd.read_csv('data.csv', dtype_backend='pyarrow')

PyArrow 백엔드의 장점:

  • null 을 모든 타입에서 지원 (NumPy 는 float 만)
  • 메모리 효율 향상 (columnar, compressed)
  • Apache Arrow 생태계 (Polars, DuckDB, Spark) 와 무복사 교환

자세히: Pandas PyArrow Backend, [[Pandas Nullable Types (Int64, boolean, string[pyarrow])]]

핵심 자료형

flowchart LR
    DF["DataFrame\n(2D 테이블)"]
    SR["Series\n(1D 열)"]
    IX["Index\n(행/열 라벨)"]

    DF --"df['col'] → Series"--> SR
    DF --"df.index / df.columns"--> IX
    SR --"s.index"--> IX
    SR --"s.to_frame()"--> DF

Series

s = pd.Series([10, 20, 30], index=['a', 'b', 'c'], name='score')
s.dtype   # int64
s.index   # Index(['a', 'b', 'c'])

DataFrame

df = pd.DataFrame({'x': [1, 2], 'y': [3, 4]})
df.columns  # Index(['x', 'y'])
df['x']     # Series

Index

행과 열 모두 Index 객체. RangeIndex, DatetimeIndex, MultiIndex 등 여러 서브타입이 있다.

자세히: Pandas Series, Pandas DataFrame, Pandas Index

어디에 쓰는가

영역
데이터 ETLCSV/Excel/DB 읽기 → 정제 → 저장
탐색적 분석 (EDA)describe(), value_counts(), 시각화
ML 전처리결측치 처리, encoding, scaling
시계열 분석resample, rolling, 이동평균
보고서 자동화pivot/groupby + 차트

주요 I/O

# 읽기
df = pd.read_csv('data.csv')
df = pd.read_excel('data.xlsx')
df = pd.read_parquet('data.parquet')
df = pd.read_sql('SELECT * FROM t', conn)

# 쓰기
df.to_csv('out.csv', index=False)
df.to_parquet('out.parquet')
df.to_json('out.json', orient='records', lines=True)

자세히: Pandas read_csv, Pandas read_excel, Pandas read_parquet, Pandas read_sql

학습 경로

  1. 자료형 이해: Pandas Series, Pandas DataFrame, Pandas Index
  2. I/O: Pandas read_csv, Pandas read_excel
  3. 선택: Pandas .loc / .iloc, Pandas query
  4. 필터링: Pandas Boolean Indexing
  5. 그룹/집계: Pandas groupby
  6. 변형: Pandas pivot, Pandas melt
  7. 결합: Pandas merge

버전 관습

버전주요 변경
0.x레거시. append(), Panel 등 deprecated API
1.xnullable Int64/boolean dtypes, pd.NA 도입
2.0 (2023)Copy-on-Write, PyArrow 백엔드, int64 기본 nullable
2.1infer_string 옵션 (str → ArrowDtype)
2.2Copy-on-Write 완전 기본화, Arrow-backed string 기본

본 wiki 는 2.x 기준 으로 작성. 1.x 와 차이가 있는 부분은 명시.

성능 특성

연산빠름느림
수치 벡터 연산✓ NumPy 활용-
행 단위 반복 (iterrows)-✓ Python 오버헤드 큼
대용량 필터/집계✓ C 레벨-
문자열 처리-✓ Python str 오버헤드
Arrow 백엔드 문자열✓ 개선됨-

10M+ 행 이상의 대용량 처리에는 Pandas PyArrow Backend 나 Polars/DuckDB 고려.

자세히: Pandas 성능 / 메모리 최적화

함정

WARNING

df.append() 는 pandas 2.0 에서 제거됐다. pd.concat([df, new_row]) 를 사용하라.

# ❌ pandas 1.x
df = df.append({'a': 1}, ignore_index=True)

# ✓ pandas 2.x
df = pd.concat([df, pd.DataFrame([{'a': 1}])], ignore_index=True)

CAUTION

inplace=True 는 method chaining 을 깨고 반환값이 None 이다. 일관성을 위해 inplace=False (기본) 를 권장한다.

관련 위키

이 글의 용어 (16개)
[Pandas] .loc / .ilocpandas
정의 - : 라벨 기반 인덱싱 (index/column 이름) - : 정수 위치 기반 인덱싱 (0-based) 이 두 indexer 가 pandas 선택의 표준. 만으로는 헷갈리…
[Pandas] 성능 / 메모리 최적화pandas
정의 pandas 의 흔한 성능 함정과 최적화 패턴. 벡터화 + dtype 선택 + 알고리즘 의 조합이 핵심. 사용 상황 | 상황 | 권장 접근 | |:---|:---| | 단순…
[Pandas] Boolean Indexingpandas
정의 Boolean Indexing 은 True/False 의 Series 를 인덱서로 전달 해 행을 선택하는 패턴. pandas 의 가장 흔한 필터링 방법. 마스크 생성과 적용…
[Pandas] DataFramepandas
정의 은 2차원 레이블 테이블. 각 열이 , 모든 열이 같은 (행 라벨) 를 공유. SQL 테이블 / Excel 시트 / R data.frame 의 Python 대응체. 구조 시…
[Pandas] groupbypandas
정의 는 데이터를 그룹으로 나누고 (split), 각 그룹에 함수를 적용 (apply), 결과를 합쳐 (combine) 새 DataFrame 으로 만드는 split-apply-c…
[Pandas] Indexpandas
정의 는 행 / 열 라벨을 보관하는 객체. / 의 모든 라벨은 Index. 정렬, 정합성, 빠른 lookup 의 기반. 기본은 RangeIndex (0, 1, 2, ...) 지만…
[Pandas] meltpandas
정의 는 의 역방향. wide-format → long-format 변환. 여러 컬럼을 두 컬럼 ( , ) 으로 합친다. 장기간 시계열 데이터나 시각화 라이브러리 (seaborn…
[Pandas] mergepandas
정의 는 두 DataFrame 을 SQL join 처럼 결합. 4 가지 join 타입 (inner / left / right / outer) 지원. 사용 상황 - 두 테이블 키 …
[Pandas] pivotpandas
정의 는 long-format → wide-format 변환. 한 열의 고유 값들이 새 컬럼이 되고, 원래 데이터는 그 자리에 배치된다. 집계가 없으므로 같은 (index, co…
[Pandas] PyArrow Backendpandas
정의 pandas 2.0 부터 Apache Arrow 를 백킹으로 사용 하는 새 dtype 시스템. NumPy 기반의 한계 (메모리, 문자열, 타입 다양성) 를 크게 개선. 사용…
[Pandas] query / evalpandas
정의 - : 문자열로 boolean 표현식 을 전달해 행 필터링 - : 문자열로 계산 표현식 을 평가 의 가독성 있는 대안. 사용 상황 - 조건이 복잡해 boolean index…
[Pandas] read_csv / to_csvpandas
정의 는 CSV(Comma-Separated Values) 또는 구분자 기반 텍스트 파일을 DataFrame 으로 읽는 함수. pandas 사용의 출발점. 반대 방향은 : Dat…
[Pandas] read_excel / to_excelpandas
정의 는 Excel 파일 (.xlsx, .xls) 을 으로 읽는 함수. 와 은 역방향 저장을 담당한다. 한국 실무에서 업무 보고서, 정산 파일, 외부 데이터 수신 등에 매우 자주…
[Pandas] read_parquet / to_parquetpandas
정의 Parquet 은 column-oriented binary 포맷. CSV 대비 수십 배 빠르고 작다. dtype 보존, 압축, 부분 컬럼 읽기 지원. 데이터 분석의 사실상 …
[Pandas] read_sql / to_sqlpandas
정의 - : SQL 결과 -> DataFrame - : DataFrame -> DB 테이블 SQLAlchemy 의 connection / engine 객체를 사용. 직접 sqli…
[Pandas] Seriespandas
정의 는 1차원 레이블 배열. NumPy + 의 결합. 의 한 열이 곧 Series. dict-like (key = index label) 이자 list-like (순서 있는 배…

이 개념을 다룬 위키 페이지 (2)

💬 댓글

사이트 검색 / 명령어

검색

스크롤 = 확대/축소 · 드래그 = 이동 · 0 = 원래 크기 · ESC = 닫기