机器学习特征预处理之删除常量列
·
示例
def remove_constants(X_train, X_test, threshold=1e-10):
"""
删除常量列(修复版)
数值列:使用方差阈值
非数值列:使用唯一值数量
"""
combined = pd.concat([X_train, X_test])
cols_to_keep = []
for col in combined.columns:
if pd.api.types.is_numeric_dtype(combined[col]):
if combined[col].var() > threshold:
cols_to_keep.append(col)
else:
if combined[col].nunique() > 1:
cols_to_keep.append(col)
return X_train[cols_to_keep], X_test[cols_to_keep]
调用示例
# 1. 准备数据
X_train = pd.DataFrame({
'年龄': [25, 30, 35, 40],
'身高': [170, 175, 180, 185],
'性别': ['M', 'F', 'M', 'F'],
'城市': ['北京', '上海', '北京', '深圳'],
'常量列': [1, 1, 1, 1], # 常量列(将被删除)
'几乎常量': [1.0, 1.0+1e-12, 1.0+2e-12, 1.0+3e-12] # 几乎常量(将被删除)
})
X_test = pd.DataFrame({
'年龄': [28, 32],
'身高': [172, 178],
'性别': ['M', 'F'],
'城市': ['北京', '上海'],
'常量列': [1, 1], # 常量列(将被删除)
'几乎常量': [1.0, 1.0+1e-12] # 几乎常量(将被删除)
})
print("原始数据 - 训练集:")
print(X_train)
print(f"\n训练集形状: {X_train.shape}")
print(f"列名: {X_train.columns.tolist()}")
# 调用
X_train_clean, X_test_clean = remove_constants(X_train, X_test)
print("\n处理后 - 训练集:")
print(X_train_clean)
print(f"\n处理后形状: {X_train_clean.shape}")
print(f"保留的列: {X_train_clean.columns.tolist()}")
更多推荐



所有评论(0)