pd.cut() ํจ์์ pd.cut() ํจ์๋ฅผ ์ด์ฉํ์ฌ ์์นํ ๋ณ์๋ฅผ ํน์ ๊ตฌ๊ฐ์ผ๋ก ๋๋ ๋ฒ์ฃผํ ๋ ์ด๋ธ์ ์์ฑํ ์ ์๋ค. ์ ํจ์๋ค์ ์ด์ฉํ์ฌ ํน์ ๊ตฌ๊ฐ๋ค์ ๋ํ ๊ทธ๋ฃน๋ณ ํต๊ณ๋์ ๊ตฌํ๋ ๊ฒ์ด ๊ฐ๋ฅํด์ง๋ค.
์์ ๋ ํจ์์ ์ฐจ์ด์ ์ ์๋์ ๋ํ๋ฅผ ํตํด ์ดํดํ ์ ์๋ค. cut์ ๋ฐ์ดํฐ๋ฅผ ๋์ผํ ๊ธธ์ด๋ก ๋๋๋ ๊ฒ์ด๊ณ qcut์ ๋์ผํ ๊ฐฏ์๋ก ๋๋๋ ๊ฒ์ด๋ค.
pd.cut()
๋จผ์ ์์ ๋ก ์ฌ์ฉํ ํ์ดํ๋ ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์จ๋ค.
In [1]:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
titanic = sns.load_dataset('titanic')
titanic.head()
์ ๋ฐ์ดํฐ์์ ์์นํ ๋ณ์๋ก age ์ปฌ๋ผ์ด ์กด์ฌํ๋ค. ์ด age ์ปฌ๋ผ์์ ํน์ ๊ตฌ๊ฐ์ ๋๋์ด ๋ค์ํ ์ฐ๋ น๋ ๊ทธ๋ฃน์ ๋ง๋ค๊ณ ์ถ์ ๊ฒฝ์ฐ pd.cut ํน์ pd.qcut ํจ์๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
๋จผ์ cut ํจ์์ ๋ํด ์ดํด๋ณด์
cut ํจ์์ ์ฌ์ฉ๋ฐฉ๋ฒ์ [๋ฐ์ดํฐ, ๊ตฌ๊ฐ์ ๊ฐฏ์, ๋ ์ด๋ธ๋ช ] ์ ํด๋นํ๋ ์ธ์๊ฐ์ ์ง์ ํด์ฃผ๋ ๊ฒ์ด๋ค.
labels๋ฅผ ์ง์ ํ์ง ์์ผ๋ฉด ๊ตฌ๊ฐ์ ๋๋ ๊ธฐ์ค์ด ๋ ์ด๋ธ๋ช ์ผ๋ก ์ง์ ๋๋ค.
# ๊ตฌ๊ฐ ๋ ์ด๋ธ ๋ช
์
titanic['age_class'] = pd.cut(titanic['age'], 3, labels=['child', 'young', 'old'])
titanic[['age', 'age_class']].head()
sns.displot(titanic, x='age', hue='age_class', element='step')
titanic['age_class'].value_counts()
young 345
child 319
old 50
Name: age_class, dtype: int64
ํ์ดํ๋ ๋ฐ์ดํฐ์์ age ์ปฌ๋ผ์ ๋์์ผ๋ก ์ด 3๊ฐ์ ๋์ผํ ๊ธธ์ด๋ฅผ ๊ฐ์ง๋ label์ ์์ฑํ ๊ฒ์ ํ์ธํ ์ ์๊ณ ๋์ผํ ๊ธธ์ด๋ก ์๋๊ธฐ ๋๋ฌธ์ label์ ๋ถ๊ท ํ์ด ๋ฐ์ํ๋ ๊ฒ์ ์ ์ ์๋ค.
titanic.groupby('age_class')['survived'].mean()
age_class
child 0.407524
young 0.417391
old 0.320000
Name: survived, dtype: float64
์ด๋ ๊ฒ ๋ฒ์ฃผํ ๋ฐ์ดํฐ๋ฅผ ๋ง๋ค์ด groupby๋ฅผ ํตํด ์์กด์จ์ ๋ถ์ํ ์ ์๋ค.
pd.qcut()
qcut ํจ์๋ cut ํจ์์ ๋ค๋ฅด๊ฒ ๋์ผํ ๊ธธ์ด๋ก ๊ตฌ๊ฐ์ ๋๋๋ ๊ฐ๋ ์ด ์๋ ๋์ผํ ๊ฐฏ์๋ก ๊ตฌ๊ฐ์ ๋๋๋ ํจ์์ด๋ค.
์ค์ ์์ ๋ฅผ ํตํด cut ํจ์์ ๋ฌด์์ด ๋ค๋ฅธ์ง ์ดํด๋ณด์
In [17]:
titanic = sns.load_dataset('titanic')
titanic['age_class'] = pd.qcut(titanic['age'], 3, labels=['child', 'young', 'old'])
In [19]:
sns.displot(titanic, x='age', hue='age_class', element='step')
titanic['age_class'].value_counts()
Out[20]:
child 246
old 236
young 232
Name: age_class, dtype: int64
์์ cut ํจ์์ ๋ค๋ฅด๊ฒ qcut ํจ์๋ ๋์ผํ ๊ฐฏ์๋ก ๊ตฌ๊ฐ์ ๋๋๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
In [21]:
titanic.groupby('age_class')['survived'].mean()
Out[21]:
age_class
child 0.418699
young 0.400862
old 0.398305
Name: survived, dtype: float64
๋ฐ๋ผ์ ์๋ก ๋ค๋ฅธ ๋ฐ์ดํฐ๋ฅผ ๊ทธ๋ฃนํ ํ๊ธฐ ๋๋ฌธ์ ๋ถ์ ๊ฒฐ๊ณผ์ ์์ด์๋ ์ฐจ์ด๋ฅผ ๋ณด์ผ ์ ์๋ค.
qcut ํจ์๋ฅผ ๋ณ๋์ ํจ์๋ก ๋ง๋ค์ด์ ์ฌ์ฉํ๊ณ ์ถ๋ค๋ฉด ์๋์ ์ฝ๋๋ฅผ ์ด์ฉํ์.
In [22]:
iris = sns.load_dataset("iris")
def q3cut(s):
return pd.qcut(s, 3, labels = ["์","์ค","๋"]).astype(str)
iris["petal_length_class"] = iris.groupby(iris.species).petal_length.transform(q3cut)
iris
'Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] Dataframe ์ปฌ๋ผ ์ฌ๊ตฌ์ฑ (2) | 2024.10.17 |
---|---|
[Python] Dataframe ๋ณํฉ (1) | 2024.10.17 |
[Python] Boolean Indexing (0) | 2024.10.16 |
[Python] lambda (2) | 2024.10.16 |
[Python] map, apply, applymap (0) | 2024.10.16 |