【问题标题】:How to apply LabelEncoder for a specific column in Pandas dataframe如何为 Pandas 数据框中的特定列应用 LabelEncoder
【发布时间】:2018-10-19 21:38:24
【问题描述】:

我有一个数据帧加载的数据集,其中类标签需要使用来自 scikit-learn 的LabelEncoder 进行编码。 label 列是类标签列,具有以下类:

[‘Standing’, ‘Walking’, ‘Running’, ‘null’]

为了执行标签编码,我尝试了以下方法,但它不起作用。我该如何解决?

from sklearn import preprocessing
import pandas as pd

df = pd.read_csv('dataset.csv', sep=',') 
df.apply(preprocessing.LabelEncoder().fit_transform(df['label']))

【问题讨论】:

  • 如果你只是在apply()之外单独运行preprocessing.LabelEncoder().fit_transform(df['label']),你会得到编码标签吗?
  • 是的,你是对的,错误消失了,但我没有看到编码!类没有被转换。这就是为什么我使用apply() 以便在数据框中应用转换
  • apply() 接受一个函数,它将应用于每个点。在这里,您将转换后的数据发送到 apply(),而不是函数,因此是错误。

标签: python python-3.x machine-learning scikit-learn label-encoding


【解决方案1】:

你可以尝试如下:

le = preprocessing.LabelEncoder()
df['label'] = le.fit_transform(df.label.values)

或者以下也可以:

df['label'] = le.fit_transform(df['label'])

它将用编码标签替换数据框中的原始label 值。

【讨论】:

  • 感谢您的回答。我认为有一个错误AttributeError: 'DataFrame' object has no attribute 'label'。我正在使用 Python 3.6
  • label 不是dataframe 中的列吗?还是成功了?
  • label 是包含这些值之一的类标签[‘Standing’, ‘Walking’, ‘Running’, ‘null’]
  • 是的! df['label'] = le.fit_transform(df['label']) 工作!非常感谢
【解决方案2】:

你也可以这样做:

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df.col_name= le.fit_transform(df.col_name.values)

其中 col_name = 您要标记编码的特征

【讨论】:

  • 更好的是df.col_name.values
【解决方案3】:
 from sklearn.preprocessing import LabelEncoder
 le = LabelEncoder()
 X[:, 2] = le.fit_transform(X[:, 2]) 

如果您想更改 CSV 数据中的特定列,这可能会有所帮助

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多