본문 바로가기

Data Science/Pandas

Sort 커스터마이징 (범주형 변수)

728x90
import pandas as pd
import numpy as np
from pandas.api.types import CategoricalDtype

df = pd.DataFrame({
    'cloth_id': [1001, 1002, 1003, 1004, 1005, 1006],
    'size': ['S', 'XL', 'M', 'XS', 'L', 'S'],
})
df

cat_size_order = CategoricalDtype(
    ['XS', 'S', 'M', 'L', 'XL'], 
    ordered=True
)
df['size'] = df['size'].astype(cat_size_order) # 형 변환 필수
df.sort_values('size')

 

df['size'].cat.codes

# 결과
```
0    1
1    4
2    2
3    0
4    3
5    1
dtype: int8
```

df['codes'] = df['size'].cat.codes
df

 

 

df2 = pd.DataFrame({
    'order_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007],
    'customer_id': [10, 12, 12, 12, 10, 10, 10],
    'month': ['Feb', 'Jan', 'Jan', 'Feb', 'Feb', 'Jan', 'Feb'],
    'day_of_week': ['Mon', 'Wed', 'Sun', 'Tue', 'Sat', 'Mon', 'Thu'],
})

cat_day_of_week = CategoricalDtype(
    ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], 
    ordered=True
)
cat_month = CategoricalDtype(
    ['Jan', 'Feb', 'Mar', 'Apr'], 
    ordered=True,
)

df2['day_of_week'] = df2['day_of_week'].astype(cat_day_of_week)
df2['month'] = df2['month'].astype(cat_month)
df2.sort_values(['month', 'day_of_week'])

df2.sort_values(['customer_id', 'month', 'day_of_week'])

 

 

 

참고

https://github.com/BindiChen/machine-learning/tree/main/data-analysis/018-pandas-merge

728x90
반응형