迭代列pandas将dtype对象编码为分类值

问题描述 投票:0回答:2

我有一个数据集,其中包含目前尚未编码的分类值。例如,我有一个名为condition的变量,它具有以下值:Very ExcellentExcellentVery Good

我想编码这些(给它们整数值),以便我可以在回归中将它们用作分类虚拟变量。但是,我的数据框中有很多这些,所以我想迭代每一列并编码所有dtype对象。这是我的尝试:

import pandas as pd
from sklearn.preprocessing import LabelEncoder
enc=LabelEncoder()

for column in df_06:
    if df_06["column"].values==object:
        df_06["column"]=enc.fit_transform(df_06["column"])

我的数据框是

错误:

<ipython-input-48-ea6aec86108f> in <module>() 1 for column in df_06: ----> 2 if df_06[column].values==object: 3 df_06[column]=enc.fit_transform(df_06[column]) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

python pandas loops scikit-learn encode
2个回答
1
投票

for循环有很多错误。例如,pd [“column”]不会调用value列。此外,您正在尝试将完整列与单个值“对象”(您在注释中报告的错误)进行比较。

对于您的问题,您可以使用

 for column in df.select_dtypes(include=['whatever_type_you_want']):
    df[column], _ = pd.factorize(df[column])

select_dtypes也可以接受exclude作为参数。


1
投票

在编码之前,请确保您的列表示为category

df_06[list_of_columns_to_encode].apply(lambda col: col.astype('category'))
  1. 现在如果你想进行单热编码,为什么不直接使用pd.get_dummies呢? pd.get_dummies(df_06, columns=[list_of_columns_to_encode])
  2. 如果你想使用LabelEncoder然后尝试这样的事情: le = LabelEncoder() df_06[list_of_columns_to_encode].apply(le.fit_transform) 如果你想了解更多关于如何使用相同的this字典的transform未来数据,请参阅LabelEncoder答案。
© www.soinside.com 2019 - 2024. All rights reserved.