我正在尝试对数据集中的一个热编码类别列进行编码。我正在使用以下功能:
def create_ohe(df, col):
le = LabelEncoder()
a = le.fit_transform(df_new[col]).reshape(-1,1)
ohe = OneHotEncoder(sparse=False)
column_names = [col + "_" + str(i) for i in le.classes_]
return (pd.DataFrame(ohe.fit_transform(a), columns=column_names))
在此循环中调用函数时,我收到MemoryError:
for column in categorical_columns:
temp_df = create_ohe(df_new, column)
temp = pd.concat([temp, temp_df], axis=1)
错误回溯:
MemoryError Traceback (most recent call last)
<ipython-input-40-9b241e8bf9e6> in <module>
1 for column in categorical_columns:
----> 2 temp_df = create_ohe(df_new, column)
3 temp = pd.concat([temp, temp_df], axis=1)
4 print("\nShape of final df after one hot encoding: ", temp.shape)
<ipython-input-34-1530423fdf06> in create_ohe(df, col)
8 ohe = OneHotEncoder(sparse=False)
9 column_names = [col + "_" + str(i) for i in le.classes_]
---> 10 return (pd.DataFrame(ohe.fit_transform(a), columns=column_names))
MemoryError:
答案 0 :(得分:0)
Ah内存错误表示您的计算机正在最大程度地使用内存(RAM),或者python处于最大程度的使用:Memory errors and list limits?
您可以尝试拆分a = le.fit_transform(df_new[col]).reshape(-1,1)
方法。尝试运行b= le.fit(df_new[col])
,以便使标签编码器适合完整的数据集,然后可以拆分它,而不必同时对每一行进行变换,也许有帮助。
如果b= le.fit(df_new[col])
也无法正常工作,则说明您遇到了内存问题,col
可以用列名替换。
fit_transform
是fit
和transform
的组合。