[머신러닝을 위한 파이썬] Pandas

2024. 12. 26. 02:33MOOC

1. 데이터 로드 및 기본 정보 확인

1.1 CSV 데이터 로드

import pandas as pd

# 데이터 URL
data_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data'

# 데이터 로드
df_data = pd.read_csv(data_url, sep='\s+', header=None)

# 칼럼 이름 지정
df_data.columns = [
    'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS',
    'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV'
]

# 데이터 확인
print(df_data.head())

2. Series 객체 활용

2.1 Series 생성

from pandas import Series

# 리스트로 Series 생성
example_obj = Series([1, 2, 3, 4, 5])
print(example_obj)

# 인덱스 지정
example_obj_named = Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 'd', 'e'])
print(example_obj_named)

2.2 Series 연산 및 속성

# 데이터 연산
example_obj_named = example_obj_named * 2

# 특정 조건 필터링
filtered = example_obj_named[example_obj_named > 6]

# 값과 인덱스 출력
print(filtered.values, filtered.index)

3. DataFrame 객체 활용

3.1 DataFrame 생성

raw_data = {
    'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
    'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'],
    'age': [42, 52, 36, 24, 73],
    'city': ['San Francisco', 'Baltimore', 'Miami', 'Douglas', 'Boston']
}

df = pd.DataFrame(raw_data)
print(df.head())

3.2 DataFrame 인덱싱과 필터링

# 열 선택
print(df[['first_name', 'age']])

# 행 선택
print(df.loc[1])

4. 데이터 전처리

4.1 데이터 매핑 및 치환

# 성별 데이터 매핑
df['sex_code'] = df['sex'].map({'male': 0, 'female': 1})
print(df.head())

# 값 치환
df['sex'] = df['sex'].replace({'male': 0, 'female': 1})

4.2 Apply 함수

# 칼럼별 최대값과 최소값 차이 계산
df_info = df[['earn', 'height', 'age']]
result = df_info.apply(lambda x: x.max() - x.min())
print(result)

# 데이터 변환
df_info = df_info.applymap(lambda x: -x)

5. Numpy와의 통합

5.1 Numpy 연산

import numpy as np

# DataFrame에서 Numpy 배열 추출
matrix = df.to_numpy()

# 배열 연산
sum_result = matrix[:, -3:].sum(axis=1)
print(sum_result)

6. 데이터 저장 및 출력

6.1 데이터 저장

# CSV 파일 저장
df.to_csv('output.csv', index=False)

# Numpy 파일 저장
np.save('data.npy', matrix)