파이썬 데이터 분석의 필수 도구 Pandas 라이브러리 심층 활용법

Pandas 라이브러리 소개

Pandas는 파이썬 환경에서 데이터 세정, 가공 및 분석을 위해 설계된 강력한 라이브러리입니다. 유연하고 직관적인 데이터 구조를 제공하여 복잡한 데이터 분석 작업을 효율적으로 수행할 수 있게 돕습니다.

1. Pandas 설치

터미널이나 명령 프롬프트에서 아래의 pip 명령어를 사용하여 설치할 수 있습니다.

pip install pandas

2. 핵심 데이터 구조

Pandas는 크게 두 가지 자료구조인 Series와 DataFrame을 사용합니다.

  • Series: 1차원 배열 형태의 구조로, 인덱스(Index)를 가집니다.
  • DataFrame: 행과 열로 구성된 2차원 테이블 구조로, 여러 개의 Series가 결합된 형태입니다.
import pandas as pd
import numpy as np

# Series 생성 예시
temp_data = pd.Series([22.5, 24.0, np.nan, 21.8], name="Temperature")
print(temp_data)

# DataFrame 생성 예시
product_info = {
    'ProductID': [101, 102, 103, 104],
    'Category': ['Electronics', 'Books', 'Electronics', 'Home']
}
inventory_df = pd.DataFrame(product_info)
print(inventory_df)

3. 데이터 입출력(I/O)

다양한 포맷의 파일을 읽고 쓸 수 있는 기능을 제공합니다.

# CSV 데이터 로드 및 저장
raw_data = pd.read_csv('input_file.csv')
raw_data.to_csv('processed_result.csv', index=False)

# Excel 파일 핸들링
excel_data = pd.read_excel('report.xlsx')
excel_data.to_excel('output_report.xlsx', index=False)

4. 데이터 정제 및 클렌징

실제 데이터 분석 과정에서 가장 많은 시간을 할애하는 결측치와 중복값 처리를 지원합니다.

# 결측치 처리
inventory_df.dropna(subset=['Category'], inplace=True) # 특정 열의 결측치 제거
inventory_df.fillna({'Category': 'Unknown'}, inplace=True) # 결측치 채우기

# 중복 제거
inventory_df.drop_duplicates(inplace=True)

# 데이터 타입 변환
inventory_df['ProductID'] = inventory_df['ProductID'].astype(str)

5. 데이터 필터링 및 선택

조건에 맞는 데이터를 추출하거나 특정 범위를 선택하는 방법입니다.

# 열 선택
subset = inventory_df[['ProductID', 'Category']]

# 조건 필터링
electronics_items = inventory_df[inventory_df['Category'] == 'Electronics']

# 복합 조건 필터링
filtered_items = inventory_df.query("Category == 'Home' and ProductID == '104'")

6. 집계 및 데이터 요약

데이터의 특징을 파악하기 위해 통계 정보를 생성합니다.

# 요약 통계량
print(inventory_df.describe())

# 그룹별 집계
category_stats = inventory_df.groupby('Category').count()

7. 병합과 결합

서로 다른 데이터 소스를 하나로 합치는 작업을 수행합니다.

# 공통 키를 기준으로 병합 (Merge)
full_data = pd.merge(df_left, df_right, on='user_id', how='left')

# 수직/수평 결합 (Concat)
combined_df = pd.concat([df_a, df_b], axis=0)

8. 시계열 데이터 분석

날짜와 시간 데이터를 처리하는 데 특화된 기능을 제공합니다.

# 시간 인덱스 생성
date_range = pd.date_range(start='2023-01-01', periods=10, freq='D')
ts_data = pd.Series(range(10), index=date_range)

# 리샘플링 (주 단위 합계)
weekly_sum = ts_data.resample('W').sum()

9. 고급 데이터 분석 기법

더 복잡한 분석을 위해 이상치 처리 및 특징 추출(Feature Engineering)을 수행할 수 있습니다.

from scipy import stats

# Z-score를 활용한 이상치 식별
z_scores = np.abs(stats.zscore(df['numerical_col']))
clean_df = df[z_scores < 3]

# 원-핫 인코딩 (범주형 데이터 처리)
encoded_df = pd.get_dummies(df, columns=['Category'])

# 데이터셋 분할 (머신러닝 준비)
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(df, test_size=0.25, random_state=123)

10. 데이터 시각화 연동

Matplotlib 라이브러리와 통합되어 간단한 그래프를 즉시 그릴 수 있습니다.

import matplotlib.pyplot as plt

# 선 그래프 시각화
inventory_df.plot(kind='bar', x='Category', y='ProductID')
plt.title("Product Count by Category")
plt.show()

태그: pandas python-data-analysis DataFrame Series data-preprocessing

10월 29일 19:23에 게시됨