【问题标题】:LabelEncoder in sklearn throws value comparison errorsklearn中的LabelEncoder抛出值比较错误
【发布时间】:2023-04-02 20:55:01
【问题描述】:

执行以下代码时,出现错误“'

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for column in df8.columns:
  if df8[column].dtype == type(object):
    df8[column] = le.fit_transform(df8[column])

【问题讨论】:

  • 检查你的数据是否包含 NaN ?
  • @Wen:是的。但我已经用 df8=df8.fillna("")
  • 这是工作吗? df8[column] = le.fit_transform(df8[column].astype(str)
  • @Wen:谢谢,但效果不好

标签: python pandas


【解决方案1】:

您可以在下面看到您提供的 sn-p 作品。我还尝试了您填充 NaN 的方法,它仍然有效。重新启动您的 IDE 并检查您的数据框包含的其他内容可能是值得的。

import pandas as pd
from sklearn.preprocessing import LabelEncoder

df = pd.DataFrame(
        {'Country':['China', 'India', 'USA', 'Indonesia', 'Brasil', 'Japan'],
         'Population, M': [1403.5, 1324.2, 322.2, 261.1, 207.6, 127.6],
         'Label': ['huge', 'huge', 'big', 'big', 'big', 'big']})

print(df)

le = LabelEncoder()
for column in df.columns:
  if df[column].dtype == type(object):
    df[column] = le.fit_transform(df[column])

print(df)

     Country Label  Population, M
0      China  huge         1403.5
1      India  huge         1324.2
2        USA   big          322.2
3  Indonesia   big          261.1
4     Brasil   big          207.6
5      Japan   big          127.6
Out[78]: 
   Country  Label  Population, M
0        1      1         1403.5
1        2      1         1324.2
2        5      0          322.2
3        3      0          261.1
4        0      0          207.6
5        4      0          127.6

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 1970-01-01
    • 2017-01-23
    • 2017-08-13
    • 2017-06-06
    • 2019-04-16
    • 2017-12-10
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多