Python版本:Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
Pandas版本:0.19.2
系統版本:Windows 10
Pandas版本:0.19.2
系統版本:Windows 10
在資料分析中,時常會遇到要將類別資料與數值資料間轉換的情況
numerical variable to categorical variable or categorical variable to numerical variable
import pandas as pd
# create dataframe
number = [1,2,3,4,5]
sex = ['male','female','female','female','male']
df_new = pd.DataFrame()
df_new['number'] = number
df_new['sex'] = sex
df_new.head()
# create def for category to number 0/1
def tran_cat_to_num(df):
if df['sex'] == 'male':
return 1
elif df['sex'] == 'female':
return 0
# create sex_new
df_new['sex_new']=df_new.apply(tran_cat_to_num,axis=1)
df_new
沒有留言:
張貼留言