prasadpradyumna
prasadpradyumna

Reputation: 13

How can I convert some columns of a pandas dataframe to categorical?

This is my code:

l1 = list(train)
for i in (0,len(l1)):
    if train[l1[i]].dtypes == object:
        train[l1[i]] = pd.Categorical(train[l1[i]])

train.info(verbose=True)

But this just makes the first variable change and nothing else. The rest of the 62 object variables aren't converted to object.

How do you do it?

Upvotes: 1

Views: 52

Answers (1)

jezrael
jezrael

Reputation: 863801

Get all object columns by DataFrame.select_dtypes, convert to dict and pass to DataFrame.astype:

train = train.astype(dict.fromkeys(train.select_dtypes('object').columns, 'category'))

Upvotes: 1

Related Questions