[데이터 기초] Pandas 1
Pandas: 파이썬 데이터 분석 라이브러리
- 1차원 자료형: 1차원 벡터 -> Series
- 2차원 자료형: 2차원 행렬 -> DataFrame
- 3차원 자료형: 3차원 텐서 -> Pannel
- 판다스는 '차원'을 중심으로 한다.
- 인덱스를 원하는대로 제작 가능하고, 원하는 정보로 접근할 수 있다.
-> 마치 딕셔너리처럼: 코드값, 날짜, 시간, 주민번호 등...
- 시간, 숫자, 텍스트 등 여러 자료형을 모두 처리하기 때문에 속도가 느리다.
-> 적당한 사이즈의 데이터 핸들링에는 유용하게 사용 가능하다.
import numpy as np
import pandas as pd
[주식 가격 데이터 핸들링]
# 값: 10000, 10300, 9900, 10500, 11000
# 1)파이썬 리스트
stock_price_list = [10000, 10300, 9900, 10500, 11000]
# 2) numpy array
stock_price_arr = np.array(stock_price_list)
# 3) pandas Series
stock_price_Series = pd.Series(stock_price_list)
stock_price_Series
0 | 10000 |
1 | 10300 |
2 | 9900 |
3 | 10500 |
4 | 11000 |
dtype: int64
[인덱싱과 슬라이싱]
stock_price_Series[[0,4]]
0 | 10000 |
4 | 11000 |
dtype: int64
stock_price_Series_index = pd.Series(
# 진짜 데이터 + 내가 원하는 값에 접근할 수 있는 인덱스
data = [10000, 10300, 9900, 10500, 11000],
index = ['2024-08-01','2024-08-02','2024-08-03','2024-08-04','2024-08-05']
)
stock_price_Series_index
2024-08-01 | 10000 |
2024-08-02 | 10300 |
2024-08-03 | 9900 |
2024-08-04 | 10500 |
2024-08-05 | 11000 |
dtype: int64
stock_price_Series_index['2024-08-02':'2024-08-04']
# 정수 인덱스로 슬라이싱하면 끝 점이 빠지지만, 내가 만든 인덱스로 하면 끝 점이 포함
2024-08-02 | 10300 |
2024-08-03 | 9900 |
2024-08-04 | 10500 |
dtype: int64
참고) dict와의 유사성
stock_price_Series_index.index
# Index(['2024-08-01', '2024-08-02', '2024-08-03', '2024-08-04', '2024-08-5'], dtype='object')
stock_price_Series_index.values
# array([10000, 10300, 9900, 10500, 11000])
[결측치 처리]
s_data = {"APPL":1000, "MS":2000, "TSLA": 1500}
s_data
# {'APPL': 1000, 'MS': 2000, 'TSLA': 1500}
s_1 = pd.Series(s_data)
s_1
APPL | 1000 |
MS | 2000 |
TSLA | 1500 |
dtype: int64
ticker = ['GOOGLE','APPL','MS','META']
s_2 = pd.Series(s_data, index = ticker)
s_2
NaN | |
APPL | 1000.0 |
MS | 2000.0 |
META | NaN |
dtype: float64
s_2.isnull()
True | |
APPL | False |
MS | False |
META | True |
dtype: bool
# 받은 데이터 중에서 결측치만 체크 -> 불리언 인덱싱 활용
s_2[s_2.isnull()]
NaN | |
META | NaN |
dtype: float64
# 반대로 결측치가 아닌 값들만 체크
s_2[s_2.notnull()]
APPL | 1000.0 |
MS | 2000.0 |
dtype: float64
**결측치 처리 시 주의사항
- NaN 이외 '', None 같은 값들도 들어가 있을 수 있다.
- 코드뿐만 아니라 실제 데이터를 보며 작업해야 한다.
[값에 대한 접근]
1. 하나의 값에 대한 접근 1) at: 내가 만든 인덱스로
2) iat: 태생적인 정수 인덱스로
2. 여러개의 값에 대한 접근 1) loc: 내가 만든 인덱스로
2) iloc: 태생적인 정수 인덱스로
- 버전에 따라 변경될 가능성이 있다.
- 속도 차이가 나기 때문에 상황에 적절한 방식으로 잘 선택해야 한다.
# 비공식적인 방법: 권장하지 않음
stock_price_Series_index[0]
#<ipython-input-74-80e6025b91d1>:2: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
stock_price_Series_index[0]
# 10000
# 정수인덱스로 0번째 1개 값에 대해 접근
stock_price_Series.iat[0]
# 10000
# 2024년 8월 4일의 주식 가격 -> 내가 만든 인덱스로 1개의 값에 접근
stock_price_Series.at['2024-08-04']
# 10500
# 0번째부터 4번째 날까지의 주식 가격
stock_price_Series.iloc[0:4]
2024-08-01 | 10000 |
2024-08-02 | 10300 |
2024-08-03 | 9900 |
2024-08-04 | 10500 |
dtype: int64
# 2024년 8월 2일부터 8월 4일까지 주식 가격
stock_price_Series.loc['2024-08-02':'2024-08-04']
2024-08-02 | 10300 |
2024-08-03 | 9900 |
2024-08-04 | 10500 |
dtype: int64
참고) 수치연산 numpy 활용
- 파이썬 함수, 외부 함수도 사용 가능하다.
stock_price_Series_index.count()
# 5
stock_price_Series_index.max()
# 11000
sum(stock_price_Series_index)
# 51700