본문 바로가기

데이터 사이언스/데이터 분석

[NIPA AI 교육/기본] Pandas 기초

Pandas란?

Python 라이브러리로, 구조화된 데이터를 효과적으로 처리하고 저장하게 도와줌.

Numpy를 기반으로 설계되어 Array 계산에 특화됨


Series 데이터 생성하기

- 하나의 컬럼 값으로만 이루어짐

- Data와 Index가 있으며, 값(values)를 ndarray 형태로 가지고 있음

- 인덱스 지정이 가능하며, 인덱스로 접근 가능

data = pd.Series([1, 2, 3, 4])
gdp_dict = {
'korea':5180
'japan':12718
'china':141500
'usa':32676
}

gdp = pd.Series(gdp_dict)
country = pd.Series([5180, 12718, 141500, 32676], index=['korea', 'japan', 'china', 'usa'], name='Country')

# 실행결과
# korea      5180
# japan     12718
# china    141500
# usa       32676
# Name: Country, dtype: int64

DataFrame

- 여러 개의 Series가 모여서 행과 열을 이룬 데이터로, python의 기본 dictionary 를 활용하여 dataframe 생성이 가능함

import numpy as np
import pandas as pd

# 두 개의 시리즈 데이터가 있습니다.
print("Population series data:")
population_dict = {
    'korea': 5180,
    'japan': 12718,
    'china': 141500,
    'usa': 32676
}
population = pd.Series(population_dict)
print(population, "\n")

print("GDP series data:")
gdp_dict = {
    'korea': 169320000,
    'japan': 516700000,
    'china': 1409250000,
    'usa': 2041280000,
}
gdp = pd.Series(gdp_dict)
print(gdp, "\n")


# 데이터프레임 생성
print("Country DataFrame")
data = {
    'population': population,
    'gdp': gdp
}
country = pd.DataFrame(data)
print(country)


# Country DataFrame
# population         gdp
# korea        5180   169320000
# japan       12718   516700000
# china      141500  1409250000
# usa         32676  2041280000

- dataframe에 index와 column 이름 지정 가능

country.index.name = 'Country'   # 인덱스 이름 지정
country.columns.name = 'info'   # 컬럼 이름 지정

- 데이터 프레임 저장 및 불러오기

country.to_csv('./country.csv')
country.to_excel('./country.xlsx')

country = pd.read_csv('./country.csv')
country = pd.read_excel('./country.xlsx')

indexing & slicing

.loc - 명시적인 인덱스를 참조하는 인덱싱/슬라이싱

# 인덱싱
country.loc['china']

# 슬라이싱
country.loc['japan':'korea', :'population']

.iloc - 정수 인덱스를 이용하여 인덱싱/슬라이싱

 

country.iloc[2]
country.iloc[1:3, :3]

 


컬럼으로 데이터 선택

country['gdp']   # Series 형태 반환

country[['gdp']]   # DataFrame 형태 반환

조건으로 데이터 선택

- Masking 연산

df[(df['A']<0.5) & (df['B']>0.3)]

- Query 함수 활용

df.query('A < 0.5 and B >0.3')

데이터 추가 및 수정

- 리스트로 데이터 추가

df.loc[0] = ['홍비', '26', '경기']

- 딕셔너리로 데이터 추가

df.loc[1] = {'이름':'홍비', '나이':'26', '주소': '경기'}

- NaN 값으로 새로운 컬럼 추가도 가능

df['주소'] = np.nan   # 새로운 컬럼 추가 후 초기화

- axis=0 : 행 방향, axis=1 : 열 방향

- inplace=True : 원본 변경, inplace=False : 원본 변경 X

df.drop('주소', axis=1, inplace=True)  # 컬럼 삭제