python - 规范化数据框的列
问题描述
我想规范化以下数据框中的列:
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
为每一列做 , 。
是否需要将标准差除以每列中的条目数?
解决方案
您的代码按列运行,并且可以正常工作。但是,如果这是您的问题,还有其他类型的规范化,您可能需要以下一些:
平均归一化(就像你做的那样):
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你会发现很多标准化方法(不仅是)已经准备好,例如StandardScaler、MinMaxScaler或MaxAbsScaler:
使用 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
我希望我对你有所帮助!
推荐阅读
- python - 如何从 .pt 文件创建 Pytorch 数据集?
- python - 生成带有可选字段的字典的函数
- ruby-on-rails - 为什么每次对 Ruby on Rails 应用程序的新请求都不会更新“过期”标头?
- python - 带有 matplotlib 的乳胶,轴标签不正确
- javascript - 消息出现时动态应用 CSS JSF + JavaScript
- html - 如何修复导航栏过渡周围的边框?
- c# - 如何从字符串中删除可能带括号的表达式?
- powerbi - 创建参数 GA 和 powerbi
- java - Maven 找不到 JAVA_HOME
- c - 如何使用正则表达式匹配包含空格、null 和换行符的日期时间字符串?