반응형

[Python 데이터 분석] 파이썬 카테고리 타입 및 cut을 이용한 범위 나누기(Python Category, cut method)

반응형


| 파이썬 카테고리 타입 및 cut을 이용한 범위 나누기


파이썬에서는 데이터프레임(DataFrame)을 이루는 시리즈(Series) 타입 자료구조를 카테고리 타입(Category Type)으로 캐스팅하여 데이터 분석에 용이하게 쓸 수 있도록 할 수 있습니다. 또한 cut 메서드를 사용하여 데이터를 특정한 값의 범위로 나누어 그룹화하는 것도 가능합니다.


아래는 그에 대한 예제를 모아놓은 것입니다.


census.csv

import pandas as pd
import numpy as np

df = pd.DataFrame(['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D'],
index=['excellent', 'excellent', 'excellent', 'good', 'good', 'good', 'ok', 'ok', 'ok', 'poor', 'poor'])
df.rename(columns={0: 'Grades'}, inplace=True)
print(df)
'''
Grades
excellent A+
excellent A
excellent A-
good B+
good B
good B-
ok C+
ok C
ok C-
poor D+
poor D
'''
# category 타입으로 타입 캐스팅
df_head = df['Grades'].astype('category').head()
print(df_head)
'''
Categories (11, object): [A, A+, A-, B, ..., C+, C-, D, D+]
'''
# 순서가 있는 category 타입으로 타입 캐스팅
grades = df['Grades'].astype('category',
categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'],
ordered=True)
print(grades.head())
'''
excellent A+
excellent A
excellent A-
good B+
good B
Name: Grades, dtype: category
'''
print(grades > 'C')
'''
excellent True
excellent True
excellent True
good True
good True
good True
ok True
ok False
ok False
poor False
poor False
Name: Grades, dtype: bool
'''
df = pd.read_csv('census.csv')
df = df[df['SUMLEV']==50]
df = df.set_index('STNAME').groupby(level=0)['CENSUS2010POP'].agg({'avg':np.average})
# 현재 있는 값들의 분포를 10등분하여 보여줌
# 히스토그램에서 각각의 값들을 특정 범위마다 집어넣는 것이라 생각하면 됨
print(pd.cut(df['avg'], 10))
print(df)
'''
STNAME
Alabama (11706.087, 75333.413]
Alaska (11706.087, 75333.413]
Arizona (390320.176, 453317.529]
Arkansas (11706.087, 75333.413]
California (579312.234, 642309.586]
Colorado (75333.413, 138330.766]
Connecticut (390320.176, 453317.529]
Delaware (264325.471, 327322.823]
District of Columbia (579312.234, 642309.586]
Florida (264325.471, 327322.823]
Georgia (11706.087, 75333.413]
Hawaii (264325.471, 327322.823]
Idaho (11706.087, 75333.413]
Illinois (75333.413, 138330.766]
Indiana (11706.087, 75333.413]
Iowa (11706.087, 75333.413]
Kansas (11706.087, 75333.413]
Kentucky (11706.087, 75333.413]
Louisiana (11706.087, 75333.413]
Maine (75333.413, 138330.766]
Maryland (201328.118, 264325.471]
Massachusetts (453317.529, 516314.881]
Michigan (75333.413, 138330.766]
Minnesota (11706.087, 75333.413]
Mississippi (11706.087, 75333.413]
Missouri (11706.087, 75333.413]
Montana (11706.087, 75333.413]
Nebraska (11706.087, 75333.413]
Nevada (138330.766, 201328.118]
New Hampshire (75333.413, 138330.766]
New Jersey (390320.176, 453317.529]
New Mexico (11706.087, 75333.413]
New York (264325.471, 327322.823]
North Carolina (75333.413, 138330.766]
North Dakota (11706.087, 75333.413]
Ohio (75333.413, 138330.766]
Oklahoma (11706.087, 75333.413]
Oregon (75333.413, 138330.766]
Pennsylvania (138330.766, 201328.118]
Rhode Island (201328.118, 264325.471]
South Carolina (75333.413, 138330.766]
South Dakota (11706.087, 75333.413]
Tennessee (11706.087, 75333.413]
Texas (75333.413, 138330.766]
Utah (75333.413, 138330.766]
Vermont (11706.087, 75333.413]
Virginia (11706.087, 75333.413]
Washington (138330.766, 201328.118]
West Virginia (11706.087, 75333.413]
Wisconsin (75333.413, 138330.766]
Wyoming (11706.087, 75333.413]
Name: avg, dtype: category
Categories (10, interval[float64]): [(11706.087, 75333.413] < (75333.413, 138330.766] <
(138330.766, 201328.118] < (201328.118, 264325.471] < ... <
(390320.176, 453317.529] < (453317.529, 516314.881] <
(516314.881, 579312.234] < (579312.234, 642309.586]]
'''
s = pd.Series([168, 180, 174, 190, 170, 185, 179, 181, 175, 169, 182, 177, 180, 171])
print(pd.cut(s,3))
'''
0 (167.978, 175.333]
1 (175.333, 182.667]
2 (167.978, 175.333]
3 (182.667, 190.0]
4 (167.978, 175.333]
5 (182.667, 190.0]
6 (175.333, 182.667]
7 (175.333, 182.667]
8 (167.978, 175.333]
9 (167.978, 175.333]
10 (175.333, 182.667]
11 (175.333, 182.667]
12 (175.333, 182.667]
13 (167.978, 175.333]
dtype: category
Categories (3, interval[float64]): [(167.978, 175.333] < (175.333, 182.667] < (182.667, 190.0]]
'''
# 각 특정 범위에 라벨을 달아서 표시하는 것도 가능
print(pd.cut(s,3,labels=['Small', 'Medium', 'Large']))
'''
0 Small
1 Medium
2 Small
3 Large
4 Small
5 Large
6 Medium
7 Medium
8 Small
9 Small
10 Medium
11 Medium
12 Medium
13 Small
dtype: category
Categories (3, object): [Small < Medium < Large]
'''



참고자료 : https://www.coursera.org/learn/python-data-analysis



반응형

이 글을 공유하기

댓글

Designed by JB FACTORY