参数必须是字符串或数字[标签编码]

2024-09-28 23:44:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将我的数据帧附加到新的数据帧,但我得到一个“参数必须是字符串或数字”错误

# 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)

Tags: the数据inledfnewforindex
2条回答

导致此错误的原因是数据实际上既有数字也有字符串。解决此问题的最佳方法是将所有数据转换为字符串,如下所示:

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

我通过追加解决了此问题,将我的追加方法更改为:

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

相关问题 更多 >