Skip to content
Advertisement

How to drop categorical columns in pandas dataframe?

I have a df where there are 60 columns in total, and 4 categorical columns, I want to make a loop to check which are numerical columns. If they are not numeric I want to drop it. I have made the below loop but this is dropping only one of the categotcal columns, and the rest remain as is. Can you please tell me what I have done wrong and how i can improve my solution.

Thank you!

numeric = modified_df._get_numeric_data().columns
for x in modified_df.columns:
    for y in numeric:
        if x == y:
            print(x)
        else:
            dropped_df = modified_df.drop('x', axis = 1)
            dropped_df

Advertisement

Answer

You can use select_dtypes:

df_new = df.select_dtypes(exclude='category')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement