我需要对数据框执行规范化,包含一个索引列和其他带有数值的列。
Index a b c
xy1 555 436 3667
xz2 4626 658 463
xr3 425 674 436
bx4 4636 6567 6346
我想对数据帧执行最大-最小规范化,删除包含 NaN 的列,并返回带有原始索引的规范化数据帧。 我正在考虑这样的事情,但是如何从循环中排除索引列,使其在返回的数据框中保持不变?
def normalize(df):
result = df.copy()
for feature_name in df.columns:
max_value = df[feature_name].max()
min_value = df[feature_name].min()
result[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
if result[feature_name].isnull().values.any():
result.drop([feature_name], axis=1, inplace=True)
print(f'Something wrong in {feature_name}, dropping this feature.')
return result
答案 0 :(得分:1)
您可以简化 min-max
缩放的实现:
s = df.set_index('Index').dropna(axis=1)
s = (s - s.min()) / (s.max() - s.min())
或者,您可以使用 MinMaxScaler
中的 sklearn.preprocessing
:
from sklearn.preprocessing import MinMaxScaler
s = df.set_index('Index').dropna(axis=1)
s[:] = MinMaxScaler().fit_transform(s)
print(s)
a b c
Index
xy1 0.030872 0.000000 0.546701
xz2 0.997625 0.036209 0.004569
xr3 0.000000 0.038819 0.000000
bx4 1.000000 1.000000 1.000000