Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to change my categorical variables into numeric form using get_dummies function by using for loop on categorical columns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading