본문 바로가기

카테고리 없음

데이터 조작 및 분석을 위한 Pandas 기본

Pandas

파이썬 라이브러리
구조화된 데이터를 효과적으로 처리하고 저장
Array 계산에 특화된 NumPy를 기반으로 설계
대용량 데이터 계산이 장점.
엑셀과 유사한 Database 를 가지고 있음.

Series 데이터

Numpy의 array가 보강된 형태 ( Data만 있던 Array 에서 Index가 추가 되었다. )
Data와 Index 를 가지고 있음.
Series는 값(values)을 ndarray 형태로 가지고 있음.
dytpe 인자로 데이터 타입을 지정할 수 있음
인덱스를 지정할 수 있고 인덱스로 접근 가능
Dictionary를 활용하여 Series 생성 가능.

import pandas as pd

data = pd.Series([1,2,3,4])
print(data)
# 인덱스  값
# 0    1
# 1    2
# 2    3
# 3    4
# dtype: int64

print(type(data))
# <class 'pandas.core.series.Series'>

print(data.values)
# [1 2 3 4]

print(type(data.values))
# <class 'numpy.ndarray'>

## dytpe 인자로 데이터 타입을 지정할 수 있음
data = pd.Series([1,2,3,4], dtype = 'float')
print(data.dtype)
# float64


## 인덱스를 지정할 수 있고 인덱스로 접근 가능
data = pd.Series([1, 2, 3, 4], index = ['a', 'b', 'c', 'd'])
print(data)
# a    1
# b    2
# c    3
# d    4
# dtype: int64
data['c'] = 5
print(data)
# a    1
# b    2
# c    5
# d    4
# dtype: int64


## Dictionary를 활용하여 Series 생성 가능.
population_dict = {
    'china' : 141500,
    'japan' : 12718,
    'korea' : 5180,
    'usa'   : 32676
}
population = pd.Series(population_dict)
print(population)
# china    141500
# japan     12718
# korea      5180
# usa       32676
# dtype: int64

데이터 프레임

여러 개의 Series가 모여서 행과 열을 이룬 데이터

생성방법 1. Series를 모아서 생성.


gdp_dict = {
    'china' : 1409250000,
    'japan' : 516700000,
    'korea' : 169320000,
    'usa'   : 2041280000,
}
gdp = pd.Series(gdp_dict)

country = pd.DataFrame({
    'gdp' : gdp,
    'population' : population
})
print(country)
#               gdp  population
# china  1409250000      141500
# japan   516700000       12718
# korea   169320000        5180
# usa    2041280000       32676

생성방법 2. Dictionary를 활용하여 DataFrame 생성.


data = {
    'country' : ['china', 'japan', 'korea', 'usa'],
    'gdp' : [1409250000, 516700000, 169320000, 2041280000],
    'population' : [141500, 12718, 5180, 32676]
}

country = pd.DataFrame(data)
print(country)
#   country         gdp  population
# 0   china  1409250000      141500
# 1   japan   516700000       12718
# 2   korea   169320000        5180
# 3     usa  2041280000       32676

country = country.set_index('country')
print(country)
#                 gdp  population
# country                        
# china    1409250000      141500
# japan     516700000       12718
# korea     169320000        5180
# usa      2041280000       32676

DataFrame 속성 확인


print(country.shape)
# (4, 2)
print(country.size)
# 8
print(country.ndim)
# 2
print(country.values)
# [[1409250000     141500]
#  [ 516700000      12718]
#  [ 169320000       5180]
#  [2041280000      32676]]

DataFrame의 index와 column에 이름 지정


country.index.name = "Country"  # 인덱스에 이름지정
country.columns.name = "Info"   # 컬럼에 이름 지정

print(country.index)
# Index(['china', 'japan', 'korea', 'usa'], dtype='object', name='Country')
print(country.columns)
# Index(['gdp', 'population'], dtype='object', name='Info')

DataFrame 저장 및 불러오기 기능.


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

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

DataFrame 데이터 선택 - Indexing/Slicing

.loc : 명시적인 인덱스를 참조하는 인덱싱/슬라이싱
.iloc : 암묵적인 인덱스를 참족하는 인덱싱/슬라이싱.
즉, 인덱스를 정의하더라도 숫자가 암묵적으로 정의 되어있음.

print(country.loc['china'])        # 인덱싱
# Info
# gdp           1409250000
# population        141500
# Name: china, dtype: int64

print(country.loc['japan':'korea', :'population']) # 슬라이싱.
# Info           gdp  population
# Country                       
# japan    516700000       12718
# korea    169320000        5180


print(country.iloc[0])      # 인덱싱
# Info
# gdp           1409250000
# population        141500
# Name: china, dtype: int64

print(country.iloc[1:3, :2])    # 슬라이싱
# Info           gdp  population
# Country                       
# japan    516700000       12718
# korea    169320000        5180

DataFrame 데이터 선택 - 컬럼선택

컬럼명 활용하여 DataFrame에서 데이터 선택 가능.

print(country)      # 데이터 프레임
# Info            gdp  population
# Country                        
# china    1409250000      141500
# japan     516700000       12718
# korea     169320000        5180
# usa      2041280000       32676

print(country['gdp'])   # 시리즈 으로 반환
# Country
# china    1409250000
# japan     516700000
# korea     169320000
# usa      2041280000
# Name: gdp, dtype: int64

print(country[['gdp']]) # 데이터프레임 으로 반환
# Info            gdp
# Country            
# china    1409250000
# japan     516700000
# korea     169320000
# usa      2041280000

DataFrame 데이터 선택 - 조건활용

Masking 연산이나 query 함수를 활용하여 조건에 맞는 DAtaFrame 행 추출 가능.


print(country[country['population'] < 10000])  # masking 연산 활용
# Info           gdp  population
# Country                       
# korea    169320000        5180

print(country.query("population > 100000"))    # query 함수 활용
# Info            gdp  population
# Country                        
# china    1409250000      141500

DataFrame 데이터 변경 - 컬럼추가

Series도 numpy array처럼 연산자 활용 가능.

gdp_per_capita = country['gdp'] / country['population']
country['gdp per capita'] = gdp_per_capita
# Info            gdp  population  gdp per capita
# Country                                        
# china    1409250000      141500     9959.363958
# japan     516700000       12718    40627.457147
# korea     169320000        5180    32687.258687
# usa      2041280000       32676    62470.314604

DataFrame 데이터 변경 - 데이터 추가/수정

Data는 리스트, 딕셔너리로 추가 가능.

df = pd.DataFrame(columns = ['이름', '나이', '주소'])   # 데이터프레임 생성
# Empty DataFrame
# Columns: [이름, 나이, 주소]
# Index: []

df.loc[0] = ['길동', '26', '서울']                         # 리스트로 데이터 추가
#   이름  나이  주소
# 0  길동  26  서울

df.loc[1] = {'이름':'철수', '나이':'25', '주소':'인천'}  # 딕셔너리로 데이터 추가
#   이름  나이  주소
# 0  길동  26  서울
# 1  철수  25  인천

df.loc[1, '이름'] = '영희'        # 명시적 인덱스를 활용하여 데이터 수정
#   이름  나이  주소
# 0  길동  26  서울
# 1  영희  25  인천

DataFrame 데이터 변경 - NaN 컬럼 추가

NaN값으로 초기화 한 새로운 컬럼 추가

df['전화번호'] = np.nan        # 새로운 컬럼 추가 후 초기화
#   이름  나이  주소  전화번호
# 0  길동  26  서울   NaN
# 1  영희  25  인천   NaN

df.loc[0, '전화번호'] = '01012341234'
#   이름  나이  주소         전화번호
# 0  길동  26  서울  01012341234
# 1  영희  25  인천          NaN

DataFrame 데이터 변경 - 컬럼삭제

DataFrame에서 컬럼 삭제 후 원본 변경

df.drop('전화번호', axis =1, inplace = True)        # 컬럼삭제
# axis = 1 : 열방향 / axis = 0 : 행방향
# inplace = True : 원본 변경 / inplace = False : 원본 변경 X