Pandas는 numpy를 기반으로 하는 파이썬의 데이터 처리 라이브러리이다.
주로 구조화된 데이터를 처리하거나 통계 분석에 사용한다.
pandas에서는 Series와 DataFrame이라고 하는 두가지 자료구조를 사용한다.
그 중, Series에 대해 알아보자.
Series
- column vector를 표현하는 데이터 객체이다.
- numpy의 ndarray의 서브 클래스(자식 클래스)이다.
- 인덱스와 값으로 이루어져 있다.
import pandas as pd
list_data = [1,2,3,4,5]
series_ex = pd.Series(data = list_data)
print(series_ex)
# 출력:
# 0 1 좌측에 인덱스, 우측에 값이 출력된다.
# 1 2
# 2 3
# 3 4
# 4 5
# dtype: int64
인덱스의 값을 원하는 값으로 지정해줄 수 있다.
list_data = [1,2,3,4,5]
index_name = ['a', 'b', 'c', 'd', 'e']
series_ex = pd.Series(data = list_data, index = index_name)
print(series_ex)
# 출력:
# a 1
# b 2
# c 3
# d 4
# e 5
# dtype: int64
print(series_ex['c']) # 출력: 3
파이썬의 list 뿐만 아니라, 파이썬의 dict 타입을 Series로 만들 수 있다.
import numpy as np
dict_data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
series_ex = pd.Series(dict_data, dtype = np.float64, name = "example_data")
print(series_ex)
# 출력:
# a 1.0
# b 2.0
# c 3.0
# d 4.0
# e 5.0
# Name: example_data, dtype: float64
dict의 key와 value가 Series에서 각각 index와 data로 변환된다.
Series는 index 값을 기준으로 생성된다.
dict_data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
index_name = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
series_ex = pd.Series(dict_data, index = index_name)
print(series_ex)
# 출력:
# a 1.0
# b 2.0
# c 3.0
# d 4.0
# e 5.0
# f NaN 인덱스의 해당하는 값이 없다면 NAN(Not a Number)
# g NaN
# h NaN
# dtype: float64
따라서, 인덱스에 해당하는 data가 존재하지 않으면 NaN (Not a Number)가 저장된다.
astype 함수
Series 또는 다음 글에서 다룰 DataFrame의 데이터 타입을 변경하는 함수이다.
[Series 또는 DataFrame].astype(변경할 타입)
list_data = [1,2,3,4,5]
series_ex = pd.Series(data = list_data)
print(series_ex.dtype) # 출력: int64
series_ex = series_ex.astype(float)
print(series_ex.dtype) # 출력: float64
'AI > Pandas' 카테고리의 다른 글
[Pandas] DataFrame 출력할 때 보여지는 데이터 개수 늘리는 방법 (0) | 2023.03.09 |
---|---|
[Pandas] apply 함수와 applymap 함수 (0) | 2023.03.09 |
[Pandas] map 함수 VS replace 함수 (0) | 2023.03.09 |
[Pandas] DataFrame과 Series 간의 연산 (0) | 2023.03.09 |
[Pandas] DataFrame (0) | 2023.03.09 |