0

I tried to encode columns as categories.

I can not work on my data frame because all columns are dtypes: object.

My code is:

categorize_column = lambda x: x.astype('category')

df.columns = df.columns.apply(categorize_column, axis=0)

I get an error:

'function' object has no attribute 'columns'

2
  • maybe df.apply(categorize_column, axis=0) Commented May 27, 2019 at 17:30
  • What is type(df)? Maybe you accidentally assigned a function to the variable name df. Commented May 27, 2019 at 18:37

1 Answer 1

2

According to the docs:

All columns in a DataFrame can be batch converted to categorical either during or after construction.

This can be done during construction by specifying dtype="category" in the DataFrame constructor:

So you have two options:

  1. specify dtype='category' during the DataFrame construction df = pd.DataFrame(data, dtype='category')
  2. convert existing DataFrame columns to dtype "category" df = df.astype('category')

df.columns in your example normally return a pandas.core.indexes.base.Index which you can think of as a list of column headers. It does not have an .apply method (pd.Series and pd.DataFrame do) and it has nothing to do with the values in your DataFrame.

Also, it seems that you accidentally assigned a function to df. If you want to try the second method, you will need to re-create your DataFrame before you do.

Sign up to request clarification or add additional context in comments.

1 Comment

@Turmacu No problem at all and welcome to SO! If you feel like I answered your question well, consider accepting the answer. You can change your decision at any time. Later, you may gain the privilege to up/downvote questions and answers. Upvoting and accepting answers is what helps push good content to the top. Comments normally serve a different role of asking for clarification, constructive criticism or adding a minor piece of information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.