encoder=LabelEncoder()
categorical_features=df.columns.tolist()
for col in categorical_features:
df[col]=encoder.fit_transform(df[col])
df.head(20)
**i want categorical_features to take columns with datatype=object
CodePudding user response:
Try this
for col in categorical_features:
if df.dtypes[col] == "object":
print('object type')
else:
print(f'something else {df.dtypes[col]}')
you can modify your code like
categorical_features=df.columns.tolist()
for col in categorical_features:
if df.dtypes[col] == "object"
df[col]=encoder.fit_transform(df[col])
CodePudding user response:
to select all object type columns in pandas you can use:
categorical_features = df.select_dtypes(include=['object'])
The select_dtypes()
was released in Pandas v 0.14.1