[pandas] Series 기본

Series

동일한 데이터 타입의 복수개의 성분으로 구성되는 자료구조이다.

  • 1차원 구조이다.
  • Numpyndarray 기반으로 되어있다.

Series 기초

PandasSeries를 이용해 만들 수 있다.

import numpy as np
import pandas as pd # pd로 줄여서 사용한다.

s = pd.Series([-1,4, 5, 99], dtype=float64)
print(s)
## 0    -1
## 1     4
## 2     5
## 3    99
## dtype: float64
print(s.values)    # [-1.  4.  5. 99.]
print(s.index)     # RangeIndex(start=0, stop=4, step=1)
print(s.dtype)     # float64

index

Series 생성 시 index option을 별도로 지정할 수 있다. 지정시 list로 표현된다. 중복도 가능하다.

s = pd.Series([1, -8, 5, 10], dtype=np.float64, index=['b','a','c','d'] )
print(s)
## b     1.0
## a    -8.0
## c     5.0
## d    10.0
## dtype: float64
print(s['c'])   # 5.0
print(s[2])     # 5.0

Slicing

숫자 index를 가지고 다른 인덱스가 있는 자료형과 같이 slicing 가능하고 문자 index를 이용해서도 가능하다.

print(s[1:3])
## a   -8.0
## c    5.0
## dtype: float64
print(s['a':'c'])
## a   -8.0
## c    5.0
## dtype: float64

(참고)

**Seriesndarray 기반이기 때문에 Boolean indexing, Fancy indexing, 그 밖의 numpy 함수나 method를 그대로 사용할 수 있다. **

dictionary를 이용한 Series

python의 dictionary를 이용해 Series를 만들어 본다.

import pandas as pd
import numpy as np

my_dict = {"떡볶이":1500, "순대":3500, "튀김":2500}
s = pd.Series(my_dict)
print(s)
## 떡볶이    1500
## 순대     3500
## 튀김     2500
## dtype: int64
s.name = "분식집"
s.index.name = '메뉴'
print(s)
## 메뉴
## 떡볶이    1500
## 순대     3500
## 튀김     2500
## Name: 분식집, dtype: int64

Series 추가 및 삭제

Series 를 추가하거나 삭제가 가능하다.

print(s)
## 떡볶이    1500
## 순대     3500
## 튀김     2500
## dtype: int64

s['주먹밥']=1000
print(s)
## 메뉴
## 떡볶이    1500
## 순대     3500
## 튀김     2500
## 주먹밥    1000
## Name: 분식집, dtype: int64
print(s)
## 메뉴
## 떡볶이    1500
## 순대     3500
## 튀김     2500
## 주먹밥    1000
## Name: 분식집, dtype: int64

s = s.drop('주먹밥')
print(s)
## 메뉴
## 떡볶이    1500
## 순대     3500
## 튀김     2500
## Name: 분식집, dtype: int64