Home > OS >  I want to change my categorical variables into numeric form using get_dummies function by using for
I want to change my categorical variables into numeric form using get_dummies function by using for

Time:11-02

I have dataset which have categorical and numeric features . I want to convert my categorical features into numeric form using for loop which iterate through only categorical variables and convert them into numeric form.

I tried this

for i in df_balanced.columns[:-1]:

    if (df_balanced[i].dtype == 'object'):
        df_new = pd.get_dummies(i[:], columns=i[:],  drop_first = True)

but it gives me empty dataframe

CodePudding user response:

Use:

#get DataFrame with categorical (non numeric columns)
df1 = df_balanced.iloc[:, :-1].select_dtypes(object)
#remove categorical and join dummies
df =  df.drop(df1.columns, axis=1).join(pd.get_dummies(df1,  drop_first = True))
  • Related