
Pandas는 파이썬 데이터 분석에서 가장 핵심이 되는 라이브러리로, 정형 데이터를 다루는 거의 모든 프로젝트에서 사용됩니다. 특히 CSV 파일 로드, 인덱스 조작, 컬럼 조회, 행·열 슬라이싱, 조건 필터링, 그룹 분석, 결측치 처리 등 데이터 분석의 모든 단계에서 핵심적인 역할을 합니다.
본 글에서는 Pandas의 기본 개념부터 실무에서 자주 사용하는 기능까지, 제공된 코드를 바탕으로 체계적으로 정리합니다.
1. Pandas란 무엇인가?
Pandas는 표 형태(tabular)의 데이터를 효율적으로 처리하고 분석하기 위한 라이브러리입니다.
주요 구성 요소는 다음과 같습니다.
Series
1차원 데이터 구조 (ex: 한 개의 컬럼)
DataFrame
2차원 행·열 구조의 테이블 형태 데이터
Excel과 유사한 구조이며 대부분의 분석 작업은 DataFrame을 중심으로 진행됩니다.
2. DataFrame 생성하기: List → Dictionary → DataFrame
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr = [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]
import pandas as pd
my_dict = {'country': names, 'drives_right': dr, 'cars_per_cap': cpc}
cars = pd.DataFrame(my_dict)
print(cars)
포인트
- 딕셔너리를 이용하면 DataFrame 생성이 가장 쉽습니다.
- Key는 컬럼명, Value는 리스트 형태의 데이터입니다.
3. DataFrame에 인덱스(index) 설정
row_labels = ['US', 'AUS', 'JPN', 'IN', 'RU', 'MOR', 'EG']
cars.index = row_labels
print(cars)
기본 인덱스(0,1,2…)가 아닌, 국가별 라벨을 직접 지정해 더 직관적인 분석이 가능합니다.
4. CSV 파일 읽기: read_csv()
cars = pd.read_csv('cars.csv')
print(cars)
인덱스가 첫 번째 컬럼일 경우 다음처럼 설정합니다.
cars = pd.read_csv('cars.csv', index_col=0)
5. 컬럼 선택하기 (Series vs DataFrame)
print(cars['country']) # Series
print(cars[['country']]) # DataFrame
print(cars[['country', 'drives_right']])
- cars['country'] → 1차원 Series
- cars[['country']] → 2차원 DataFrame
실무에서 DataFrame 형태를 유지하는 것이 안정적일 때가 많습니다.
6. 행 선택하기: head(), iloc(), loc()
head(): 앞에서 몇 줄 보기
cars.head(조회하고자 할 수)
iloc: 위치 기반 인덱싱
cars.iloc[[3,4,5], :]
loc: 위치 기반 인덱싱
cars.loc[['AUS', 'EG']]
둘의 차이:
- iloc → 숫자 위치
- loc → 행 라벨
7. 행·열 단일 값 접근
cars.loc["MOR", "drives_right"]
또는 복수 지정:
cars.loc[["RU","MOR"], ["country","drives_right"]]
8. 새로운 컬럼 추가하기
dict = {
"name":['a','b','c','d'],
"year":[2002,2003,2004,2005],
"gender":["f","m","f","m"]
}
data_df = pd.DataFrame(dict)
data_df["comments"] = None
새로운 컬럼명을 설정하고 단일 값이나 리스트 입력하면 자동 추가됩니다.
9. 리스트·NumPy 배열을 DataFrame으로 변환
list1 = [1,2,3]
array1 = np.array(list1)
pd.DataFrame(list1, columns=["col1"])
pd.DataFrame(array1, columns=["col1"])
10. 예제
(1) . head(), tail(), shape, info(), describe()로 데이터 구조 파악
titanic_df = pd.read_csv("./path/titanic_train.csv")
titanic_df.head(5)
titanic_df.tail(5)
titanic_df.shape
titanic_df.columns
titanic_df.index
titanic_df.info()
titanic_df.describe()
핵심 기능
- head/tail → 상·하단 데이터 확인
- shape → (행, 열 수)
- columns/index → 구조 확인
- info → 결측치, 데이터 타입
- describe → 통계 정보(숫자 컬럼만)
(2) value_counts() : 데이터 값 분포 확인
titanic_df["Pclass"].value_counts()
titanic_df["Embarked"].value_counts(dropna=False)
데이터의 빈도 분석을 빠르게 수행할 수 있습니다.
(3) 컬럼 추가/수정
titanic_df["Age_New1"] = titanic_df["Age"] * 2
titanic_df["Age_New2"] = None
(4) 컬럼 삭제: drop()
titanic_df_drop = titanic_df.drop("Age_New1", axis=1)
titanic_df_drop = titanic_df.drop(["Age_New1","Age_New2"], axis=1)
axis=1 → 컬럼 삭제
axis=0 → 행 삭제
(5) 인덱스 재설정: reset_index()
titanic_df.reset_index(inplace=True)
기존 인덱스를 컬럼으로 보내고 새로운 숫자 인덱스 생성.
(6) iloc, loc, Boolean Indexing
iloc
data_df.iloc[0:2,1:3]
loc
data_df.loc["two", "gender"]
Boolean Indexing
titanic_df[titanic_df["Age"] > 60]
titanic_df[(titanic_df["Age"] > 60) & (titanic_df["Pclass"] == 1)]
데이터 분석에서 가장 많이 사용하는 필터링 방식입니다.
(7) 데이터 정렬: sort_values()
titanic_df.sort_values(by=["Age"], ascending=False)
titanic_df.sort_values(by=["Name", "Age"])
여러 컬럼 기준 복합 정렬도 가능합니다.
(8) Aggregation(집계) 함수: sum, mean, count…
titanic_df.count()
titanic_df[["Age", "Fare"]].mean()
titanic_df[["Age", "Fare"]].sum()
(9) groupby: 그룹별 분석
titanic_df.groupby("Pclass").count()
titanic_df.groupby("Pclass")[["PassengerId","Survived"]].count()
titanic_df.groupby("Pclass")["Age"].agg([max, min])
그룹 분석은 데이터 분석 실무에서 필수 기능입니다.
(10) 결측치 처리: isna(), fillna()
titanic_df.isna().sum()
titanic_df["Cabin"] = titanic_df["Cabin"].fillna("C0000")
titanic_df["Age"] = titanic_df["Age"].fillna(titanic_df["Age"].mean())
- 결측치 유무 확인
- 평균값/지정값으로 대체 가능
(11) apply + lambda로 데이터 전처리
titanic_df["Name_len"] = titanic_df["Name"].apply(lambda x: len(x))
조건부 변환
titanic_df["Child_Adult"] = titanic_df["Age"].apply(lambda x: "Child" if x <= 15 else "Adult")
복잡한 함수 적용
def get_category(age):
...
titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x: get_category(x))
apply는 실무 데이터 전처리에서 매우 강력한 도구입니다.
본 글에서는 Pandas의 핵심 기능들을 기초 → 데이터 읽기 → 조회 → 전처리 → 정렬 → 집계 → 그룹 분석 → 결측치 처리 → apply 활용 순으로 정리했습니다.
Pandas는 데이터 분석 Workflow의 중심 도구이므로 본 글의 내용을 충분히 익히면 CSV 데이터 처리, 분석 프로젝트, 머신러닝 전처리까지 폭넓게 활용할 수 있습니다.
'Programming' 카테고리의 다른 글
| Matplotlib 완전 정리: 기본 리스트/딕셔너리로 배우는 Line Plot · Scatter Plot · Histogram (0) | 2025.12.08 |
|---|---|
| NumPy 완전 정리: ndarray 생성부터 reshape, axis, 벡터와 행렬 연산까지 한 번에 배우기 (0) | 2025.12.08 |
| 파이썬 논리연산자 AND·OR·NOT 완전 정리 + NumPy 논리 연산 활용법 (1) | 2025.12.08 |
| 파이썬 딕셔너리(Dictionary) 완전 정리: 기본 개념부터 추가·수정·삭제·중첩 딕셔너리까지 (0) | 2025.12.08 |
| 리스트 복사, 탐색, 추가·반전까지: Python 리스트 기본기 완전 정리 (0) | 2025.12.08 |