์ ํ ํ๊ท๋ฅผ ์ํํ๊ณ ๋ฒ์ฃผํ ๋ณ์๋ฅผ ์ธ์ฝ๋ฉํ ๋ ์๋ฒฝํ ๊ณต์ ์ฑ์ด ๋ฌธ์ ๊ฐ ๋ ์ ์์ต๋๋ค. ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์ ์๋ ์ ๊ทผ ๋ฐฉ์์ n-1๊ฐ์ ์ด์ ์ฌ์ฉํ๋ ๊ฒ์
๋๋ค. pd.get_dummies()
์ธ์ฝ๋ฉ๋๋ ๊ฐ ๋ฒ์ฃผํ ์ด์ ๋ํด n-1์ ๋ฐํํ๋ ๋ถ์ธ ๋งค๊ฐ๋ณ์๊ฐ ์์ผ๋ฉด ์ ์ฉํฉ๋๋ค.
์์:
>>> df
Account Network Device
0 Account1 Search Smartphone
1 Account1 Display Tablet
2 Account2 Search Smartphone
3 Account3 Display Smartphone
4 Account2 Search Tablet
5 Account3 Search Smartphone
>>> pd.get_dummies(df)
Account_Account1 Account_Account2 Account_Account3 Network_Display \
0 1 0 0 0
1 1 0 0 1
2 0 1 0 0
3 0 0 1 1
4 0 1 0 0
5 0 0 1 0
Network_Search Device_Smartphone Device_Tablet
0 1 1 0
1 0 0 1
2 1 1 0
3 0 1 0
4 1 0 1
5 1 1 0
๋์ drop_first=True
์ get_dummies()
drop_first=True
์ ๊ฐ์ ๋งค๊ฐ๋ณ์๊ฐ ์๊ณ ๋ค์๊ณผ ๊ฐ์ด ์๋ํฉ๋๋ค.
>>> new_df = pd.DataFrame(index=df.index)
>>> for i in df:
new_df = new_df.join(pd.get_dummies(df[i]).iloc[:, 1:])
>>> new_df
Account2 Account3 Search Tablet
0 0 0 1 0
1 0 0 0 1
2 1 0 1 0
3 0 1 0 0
4 1 0 1 1
5 0 1 1 0
์ถ์ฒ
http://fastml.com/converting-categorical-data-into-numbers-with-pandas-and-scikit-learn/
http://stackoverflow.com/questions/31498390/how-to-get-pandas-get-dummies-to-emit-n-1-variables-to-avoid-co-lineraity
http://dss.princeton.edu/online_help/analysis/dummy_variables.htm
ํ ๋ฆฌํ์คํธ ์ ์ถ์ ๊ด์ฌ์ด ์์ผ์ ๊ฐ์?
:+1:
'์ฒซ ๋ฒ์งธ'๋ฟ๋ง ์๋๋ผ ํน์ ๊ฐ์ ๋๋กญํ ์ ์๋๋ก ํ๋ ๊ฒ์ด ์ ๋ฆฌํฉ๋๋ค.
์๋ต๋ ๋ฒ์ฃผ(์ฐธ์กฐ ๊ทธ๋ฃน)๋ ๊ณ์ ํด์์ ์ํฅ์ ์ค๋๋ค.
์๋ฅผ ๋ค์ด, ํ ๊ฐ์ง ๋ชจ๋ฒ ์ฌ๋ก๋ '๊ฐ์ฅ ํฐ' ๊ฐ์ ์ฐธ์กฐ ๋ฒ์ฃผ๋ก ์๋ตํ๋ ๊ฒ์ ๋๋ค.
````
ํซ = df[['vol_k', 'ํ์ฑํ']]
cat_vars = list(df.select_dtypes(include=['์นดํ
๊ณ ๋ฆฌ']).columns)
cat_vars์ var:
์๋ก์ด = pd.get_dummies(df[var])
ํซ = ํซ.์กฐ์ธ(์ ๊ท)
#drop most frequent variable for ref category
drop_col = df.groupby([var]).size().idxmax()
hot.drop(drop_col, axis=1, inplace=True)
print(var + " dropping " + drop_col)
print(df.groupby([var]).size())`
```
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
'์ฒซ ๋ฒ์งธ'๋ฟ๋ง ์๋๋ผ ํน์ ๊ฐ์ ๋๋กญํ ์ ์๋๋ก ํ๋ ๊ฒ์ด ์ ๋ฆฌํฉ๋๋ค.
์๋ต๋ ๋ฒ์ฃผ(์ฐธ์กฐ ๊ทธ๋ฃน)๋ ๊ณ์ ํด์์ ์ํฅ์ ์ค๋๋ค.
์๋ฅผ ๋ค์ด, ํ ๊ฐ์ง ๋ชจ๋ฒ ์ฌ๋ก๋ '๊ฐ์ฅ ํฐ' ๊ฐ์ ์ฐธ์กฐ ๋ฒ์ฃผ๋ก ์๋ตํ๋ ๊ฒ์ ๋๋ค.
````
ํซ = df[['vol_k', 'ํ์ฑํ']]
cat_vars = list(df.select_dtypes(include=['์นดํ ๊ณ ๋ฆฌ']).columns)
cat_vars์ var:
์๋ก์ด = pd.get_dummies(df[var])
ํซ = ํซ.์กฐ์ธ(์ ๊ท)
```