dataset = pd.read_csv('bank.csv',index_col=0)
X = dataset.iloc[:,:].values
Z = pd.DataFrame(X)
print(Z)
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
Z = pd.DataFrame(X)
print(Z)
但是对于列,它只能转换1个单列。我如何才能将tmore列(如第1,2,3列)转换在一起。 我试图将“ 0”更改为“ 0:”,但随后出现错误,提示“ ValueError:输入形状错误(11162,16)”。 并且如果我将X [:,0]更改为X [:,1,2,3 ...],那么它就带有“ IndexError:数组索引过多”的错误提示
答案 0 :(得分:0)
我有一个可以为您完成工作的功能:
# Own implementation of One Hot Encoding - Data Transformation
def convert_to_binary(df, column_to_convert):
categories = list(df[column_to_convert].drop_duplicates())
for category in categories:
cat_name = str(category).replace(" ", "_").replace("(", "").replace(")", "").replace("/", "_").replace("-", "").lower()
col_name = column_to_convert[:5] + '_' + cat_name[:10]
df[col_name] = 0
df.loc[(df[column_to_convert] == category), col_name] = 1
return df
# One Hot Encoding
print("One Hot Encoding categorical data...")
columns_to_convert = [col1,col2]#Enter your column names here that you want to one hot encode.
for column in df_all.columns: #columns_to_convert
if df_all.column.dtype == 'category':
df_all = convert_to_binary(df=df_all, column_to_convert=column)
df_all.drop(column, axis=1, inplace=True)
print("One Hot Encoding categorical data...completed")
请确保在columns_to_convert中输入列列表(如果您不想转换所有类别变量)。