我试图将我的数据帧附加到新的数据帧,但我得到一个“参数必须是字符串或数字”错误
# 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)
导致此错误的原因是数据实际上既有数字也有字符串。解决此问题的最佳方法是将所有数据转换为字符串,如下所示:
我通过追加解决了此问题,将我的追加方法更改为:
df_ohc = pd.concat([df_ohc, new_df], axis=1)
相关问题 更多 >
编程相关推荐