본문 바로가기

Python/Pandas

Pandas _ Category using .loc & cut Method

이번 포스팅도 데이터를 전처리 하는데 있어 중요하다고 할 수 있는 부분이다. 이것도 마찬가지로 해당 메소드의 사용법을 모르면 반복문 혹은 조건문들을 조합해 작성해야 하는 수고로움이 있다

 

 


"""
0. 수익률 구하기
1. Category준비(PER값에 따라 group number 부여하기)
2. Cut 메소드 사용
"""
#%%
import numpy as np
import pandas as pd

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

pd.set_option('display.float_format', lambda x: '%.3f' % x)
pd.set_option('max_columns', None)

df = pd.read_csv()

#%%

# 0. 수익률 구하기
df['rtn'] = df['price2'] / df['price'] - 1

# 1. Category _ PER값에 따라 group number 부여하기 (boolean selection & loc 사용)
bound1 = df['PER(배)'] >= 10
bound2 = (5<=df['PER(배)']) & (df['PER(배)']<10)
bound3 = (0<=df['PER(배)']) & (df['PER(배)']<5)
bound4 = df['PER(배)']<0

df.loc[bound1, 'PER_Score'] = 1 # bound1에 해당하는 기준에 새로운 컬럼인 PER_Score에 '1'값을 부여하기
df.loc[bound2, 'PER_Score'] = 2 # bound1에 해당하는 기준에 새로운 컬럼인 PER_Score에 '1'값을 부여하기
df.loc[bound3, 'PER_Score'] = 3 # bound1에 해당하는 기준에 새로운 컬럼인 PER_Score에 '1'값을 부여하기
df.loc[bound4, 'PER_Score'] = 4 # bound1에 해당하는 기준에 새로운 컬럼인 PER_Score에 '1'값을 부여하기

df['PER_Score'].head()
df['PER_Score'].nunique() # df['PER_Score']에서 
df['PER_Score'].value_counts()

# Nan값 여부 판단하기
df['PER_Score'].hasnans
df['PER_Score'].isna().sum()
df['PER(배)'].isna().sum()
df[df['PER(배)'].isna()]
df.loc[df['PER_Score'].isna(), "PER_Score"] = 0

# 2. Category _ PER값에 따라 group number 부여하기 (boolean series의 연산 특성 사용)
df.loc[:,'PER_Score1'] = (bound1 * 1) + (bound2 *2) + (bound3*3) + (bound4 * -1)
df['PER_Score1'].head()
df['PER_Score1'].value_counts()
df['PER_Score'].value_counts()

# 두개의 Series가 같은지 확인하는 방법
df['PER_Score'].equals(df['PER_Score1'])
df['PER_Score'].dtypes
df['PER_Score1'].dtypes
df['PER_Score'].astype(int).equals(df['PER_Score1'])

# 3. Cut을 이용해 분류하는 방법
bins = [-np.inf, 10, 20, np.inf]
labels = ['저평가기준', '보통주', '고평가주']
per_cuts2 = pd.cut(df['PER(배)'], bins = bins, labels = labels)
per_cuts2.head()

'Python > Pandas' 카테고리의 다른 글

Pandas _ row 추가하기 (loc & append)  (0) 2021.01.12
Pandas _ qcut(균할분등) & groupby()  (0) 2021.01.11
Pandas _ About Nan  (0) 2021.01.04
Pandas _ 1. 추출(정렬) _ 2. Boolean Selection _ 3. isin()  (0) 2021.01.03
Pandas _ Sort  (0) 2021.01.02