【问题标题】:Argument must be a string or number [ Label Encoding ]参数必须是字符串或数字 [标签编码]
【发布时间】:2020-09-17 14:33:53
【问题描述】:

我正在尝试将我的数据框附加到新的数据框,但我收到“参数必须是字符串或数字”错误。

# The encoders
le = LabelEncoder()
ohc = OneHotEncoder()
for col in num_ohc_cols.index:

   # Integer encode the string categories
   dat = le.fit_transform(df_ohc[col]).astype(np.int)
   # Remove the original column from the dataframe
    df_ohc = df_ohc.drop(col,axis=1)
   # One hot encode the data--this returns a sparse array
   new_dat = ohc.fit_transform(dat.reshape(-1,1))
   # Create unique column names

   n_cols = new_dat.shape[1]

   col_names = ['_'.join([col,str(x)]) for x in range(n_cols)]
   print(col_names)
   # Create the new dataframe

我在创建新数据框时遇到了错误:

new_df=pd.DataFrame(
 new_dat.toarray(),index=df_ohc.index,columns=col_names)

【问题讨论】:

  • 您能否提供一个您正在使用的返回此错误的代码示例?
  • 对不起我编辑了。
  • 在代码中 {new_df=pd.DataFrame(new_dat.toarray(),index=df_ohc.index,columns=col_names)}

标签: python pandas machine-learning scikit-learn label-encoding


【解决方案1】:

这个错误是因为你的数据实际上有一个数字和一个字符串。解决此问题的最佳方法是将所有数据转换为字符串,如下所示:

new_df = new_df.apply(lambda x: le.fit_transform(x.astype(str)), axis=0, result_type='expand')

【讨论】:

    【解决方案2】:

    我通过追加更改我的追加方法来解决:

    df_ohc = pd.concat([df_ohc, new_df], axis=1)

    【讨论】:

      猜你喜欢
      • 2020-03-11
      • 1970-01-01
      • 2020-05-05
      • 2017-05-06
      • 2019-11-04
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多