안녕하세요 미니빅입니다.

 

오랜만에 포스팅을 합니다.

 

이번 시간은 pandas 모듈에 대해서 시작해보도록 할께요.

 

앞 포스팅을 생각해보면,

 

자료형에는 숫자(int, float), 문자(str) 등의 기초 자료형들과

 

리스트, 튜플, 딕셔너리 와 같은 복합 자료형 등이 있습니다.

 

이러한 자료형은, 클래스마다, 모듈마다 다른 형태로 가지고 있는 경우도 있죠

 

대표적인게, numpy 라이브러리에서는 array, pandas에서는 Series, DataFrame가 있습니다.

 

 

그래서 우선적으로, Series에 대해서 정리해보도록 할께요.

 

Series 같은 경우는 리스트 + 딕셔너리의 형태를 띄고 있습니다.

(두 자료형을 알아야 이해하기 휠씬 쉽겠죠?)

 

리스트 - index개념을 가지고 있는 여러 가지 값을 넣을 수 있는 자료형

scores = [10,20,30]

print(scores[1])#20

 

딕셔너리 - key-value의 쌍을 가지고 있는 자료형 

subject_scores = {"math": 50, "korean":40}

print(subject_scores["korean"])#40

 

위의 예와 같습니다.

 

 

두 특성을 다 가지고 있는 시리즈에 대해서, 설명을 할께요

 

import pandas as pd
#pd라고 줄여서 쓰는 편입니다.

scores = [10,20,30]

scores=pd.Series(scores)

print(scores)

#0    10
#1    20
#2    30
#dtype: int64

위의 리스트 값을 가져와서 pandas(이하 pd)의 Series에 넣으면, Series 자료형을 가지게 됩니다.

 

출력 결과는 위와 같이 나오게 되고,

 

print(scores[2])#30

리스트처럼 index 개념도 가지고 있는 1차원 자료형입니다.

 

하지만, 출력을 보면, index가 같이 출력되는 것을 볼 수 있죠?

 

저러한 index가 자동으로 들어가서, key 이자 index가 되는 것입니다.

 

-index-

print(f"scores.index:{scores.index}")

위의 코드를 실행시키면 아래와 같이 index가 들어갑니다.

scores.index:RangeIndex(start=0, stop=3, step=1)
#0,1,2

-key-

print(f"scores.keys:{scores.keys()}")

역시 실행시키면,

scores.keys:RangeIndex(start=0, stop=3, step=1)

index와 같은 결과가 나옵니다.

 

이러한 index에는 딕셔너리처럼 값을 직접 넣을 수도 있습니다.

 

#scores=pd.Series(data=scores,index=["zero","one","two"])
scores=pd.Series(scores,["zero","one","two"])

print(scores[2])#30
print(scores["two"])#30

print(scores)

# zero    10
# one     20
# two     30
# dtype: int64

print(f"scores.index:{list(scores.index)}")
print(f"scores.keys:{list(scores.keys())}")

#scores.index:['zero', 'one', 'two']
#scores.keys:['zero', 'one', 'two']

위와 같이 index 검색도, key 값으로써 검색도 가능해집니다.

 

또한, 애초에 딕셔너리 형태로 입력도 가능합니다.

subject_scores = pd.Series(subject_scores)

print(subject_scores)

#math      50
#korean    40
#dtype: int64

print(subject_scores[0])#50
print(subject_scores["korean"])#40

역시 index, key 모두 검색이 가능합니다.

 

 

그렇다면, Series에 2차원 값을 넣으면 어떻게 될까요?

scores=pd.Series(scores,index=["zero","one"])

print(scores[1])#[20, 30, 40]
print(scores["one"])#[20, 30, 40]

print(scores)

print(scores[1][1])#30

# zero    [10, 20, 30]
# one     [20, 30, 40]
# dtype: object

위와 같이 출력되며 이 형태는, 추후 DataFrame 형태와 비교해서 꼭 보시길 바랍니다.

 

 

Series에 item(value)를 추가하는 경우엔,

 

list 자료형처럼 append 메서드를 통해서 추가해야합니다.

scores = [[10,20,30],[20,30,40,50]]
scores=pd.Series(scores,["zero","one"])

scores = scores.append(pd.Series([40],index=["one"]))

#zero        [10, 20, 30]
#one     [20, 30, 40, 50]
#one                   40

새로운 값을 추가해도, 기본적으로 새로운 key-value의 형태로 들어갑니다.

 

-삭제-

Series=Series.drop("index")

scores=scores.drop("zero")

print(scores)

#one    [20, 30, 40, 50]
#dtype: object

 

-정렬-

Series = Series.sort_index() - index 순으로 정렬

 

Series = Series.sort_values(axis:0-default) - index 순으로 정렬(기본으로 0번째 열 값으로 정렬)

 

-필터링-

import pandas as pd

data = [10, 5, 8, 12, 3]
series = pd.Series(data)

print(series[series.index%2==0])

# 0    10
# 2     8
# 4     3
# dtype: int64

print(series[series.values%2==0])

# 0    10
# 2     8
# 3    12
# dtype: int64

conditions = [True, True, False, False, False]
print(series[conditions])
# 0    10
# 1     5
# dtype: int64

각 값들에 대해서 if처럼 조건을 넣거나, 각 값들의 True, false를 지정해서 출력을 지정할 수 있습니다.

(개인적으로 if문 쪽을 선호)

 

이 정도로 Series와 그 기본 함수에 대해서 살펴봤고,

 

 

그 다음 시간엔 DataFrame에 대해서 얘기해볼께요

 

해당 내용은 한빛미디어의 파이썬으로 배우는 밑바닥 교과서 내용을 기본으로 첨언 했습니다

 

안녕!

+ Recent posts