Python 将列更改为分类数据时无法识别“.cat”命令

Python 将列更改为分类数据时无法识别“.cat”命令,python,pandas,Python,Pandas,我有一个包含六个分类列的数据框,我想将其更改为分类代码。我使用以下方法: cat_columns = ['col1', 'col2', 'col3'] df[cat_columns] = df[cat_columns].astype('category') df[cat_columns = df[cat_columns].cat.codes 我在熊猫1.0.5上 我得到以下错误: Traceback (most recent call last): File "<ipyt

我有一个包含六个分类列的数据框,我想将其更改为分类代码。我使用以下方法:

cat_columns = ['col1', 'col2', 'col3']
df[cat_columns] = df[cat_columns].astype('category')
df[cat_columns = df[cat_columns].cat.codes
我在熊猫1.0.5上

我得到以下错误:

Traceback (most recent call last):

  File "<ipython-input-54-80cc82e5db1f>", line 1, in <module>
    train_sample[non_loca_cat_columns].astype('category').cat.codes

  File "C:\Users\JORDAN.HOWELL.GITDIR\AppData\Local\Continuum\anaconda3\envs\torch_env\lib\site-packages\pandas\core\generic.py", line 5274, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: 'DataFrame' object has no attribute 'cat'
我不确定如何完成我要做的事情。

.cat不适用于Dataframe,因此您必须将每个列作为系列单独应用。 可以使用.apply和apply cat作为lambda函数

df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
或通过列循环并使用cat功能


我相信信息是明确的。cat适用于系列
for col in cat_columns:
    df[col] = df[col].cat.codes