簡體   English   中英

Pandas 通過迭代除索引之外的所有列來規范化 dataframe

[英]Pandas normalize dataframe by iterating over all columns but index

我需要對 dataframe 執行規范化,包含一個索引列和其他具有數值的列。

Index    a     b      c
xy1     555   436    3667
xz2    4626   658    463
xr3     425   674    436
bx4    4636   6567   6346

我想對 dataframe 執行最大最小規范化,刪除包含 NaN 的列,並返回具有原始索引的規范化 dataframe。 我正在考慮這樣的事情,但是如何從循環中排除索引列,以便它在返回的 dataframe 中保持不變?

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

您可以簡化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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM