首页 > 解决方案 > 规范化数据框的列

问题描述

我想规范化以下数据框中的列:

import pandas as pd
from pprint import pprint
d = {'A': [1,0,3,0], 'B':[2,0,1,0], 'C':[0,0,8,0], 'D':[1,0,0,1]}
df = pd.DataFrame(data=d)
df = (df - df.mean())/df.std()

我不确定标准化是按还是按列进行

我打算(x - mean of elements in the column)/ standard deviation为每一列做 , 。

是否需要将标准差除以每列中的条目数?

标签: pythondataframenormalizationmeanstandard-deviation

解决方案


您的代码按列运行,并且可以正常工作。但是,如果这是您的问题,还有其他类型的规范化,您可能需要以下一些:

平均归一化(就像你做的那样):

normalized_df=(df-df.mean())/df.std()
          A         B    C         D
0  0.000000  1.305582 -0.5  0.866025
1 -0.707107 -0.783349 -0.5 -0.866025
2  1.414214  0.261116  1.5 -0.866025
3 -0.707107 -0.783349 -0.5  0.866025

最小-最大归一化

normalized_df=(df-df.min())/(df.max()-df.min())
          A    B    C    D
0  0.333333  1.0  0.0  1.0
1  0.000000  0.0  0.0  0.0
2  1.000000  0.5  1.0  0.0
3  0.000000  0.0  0.0  1.0

使用sklearn.preprocessin你会发现很多标准化方法(不仅是)已经准备好,例如StandardScalerMinMaxScalerMaxAbsScaler

使用 sklearn 进行平均归一化:

import pandas as pd
from sklearn import preprocessing

mean_scaler = preprocessing.StandardScaler(copy=True, with_mean=True, with_std=True)
x_scaled = mean_scaler.fit_transform(df.values)
normalized_df = pd.DataFrame(x_scaled)

          0         1         2    3
0  0.000000  1.507557 -0.577350  1.0
1 -0.816497 -0.904534 -0.577350 -1.0
2  1.632993  0.301511  1.732051 -1.0
3 -0.816497 -0.904534 -0.577350  1.0

使用 sklearn MinMaxScaler 进行Min-Max 归一化:

import pandas as pd
from sklearn import preprocessing

min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(df.values)
normalized_df = pd.DataFrame(x_scaled)

          0    1    2    3
0  0.333333  1.0  0.0  1.0
1  0.000000  0.0  0.0  0.0
2  1.000000  0.5  1.0  0.0
3  0.000000  0.0  0.0  1.0

我希望我对你有所帮助!


推荐阅读