我有一个熊猫的数据框架,其中每一列都有不同的值范围。例如:
df:
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
知道我如何规范化这个数据框架的列,其中每个值都在0到1之间吗?
我想要的输出是:
A B C
1 1 1
0.765 0.5 0.7
0.8 0.7 0.18(which is 0.09/0.5)
我有一个熊猫的数据框架,其中每一列都有不同的值范围。例如:
df:
A B C
1000 10 0.5
765 5 0.35
800 7 0.09
知道我如何规范化这个数据框架的列,其中每个值都在0到1之间吗?
我想要的输出是:
A B C
1 1 1
0.765 0.5 0.7
0.8 0.7 0.18(which is 0.09/0.5)
当前回答
你可以简单地使用pandas.DataFrame。Transform1函数如下所示:
df.transform(lambda x: x/x.max())
其他回答
嘿,使用带有lambda的apply函数来加速这个过程:
def normalize(df_col):
# Condition to exclude 'ID' and 'Class' feature
if (str(df_col.name) != str('ID') and str(df_col.name)!=str('Class')):
max_value = df_col.max()
min_value = df_col.min()
#It avoids NaN and return 0 instead
if max_value == min_value:
return 0
sub_value = max_value - min_value
return np.divide(np.subtract(df_col,min_value),sub_value)
else:
return df_col
df_normalize = df.apply(lambda x :normalize(x))
要规范化一个DataFrame列,只使用本机Python。
不同的值会影响过程,例如图的颜色。
0到1之间:
min_val = min(list(df['col']))
max_val = max(list(df['col']))
df['col'] = [(x - min_val) / max_val for x in df['col']]
-1 ~ 1:
df['col'] = [float(i)/sum(df['col']) for i in df['col']]
OR
df['col'] = [float(tp) / max(abs(df['col'])) for tp in df['col']]
这是你如何使用列表推导式来做的:
[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]
睡魔和普拉文给出的解决方案很好。唯一的问题是,如果你在数据帧的其他列中有分类变量,这种方法将需要一些调整。
我对这类问题的解决方案如下:
from sklearn import preprocesing
x = pd.concat([df.Numerical1, df.Numerical2,df.Numerical3])
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
x_new = pd.DataFrame(x_scaled)
df = pd.concat([df.Categoricals,x_new])
您可以使用sklearn包及其相关的预处理实用程序来规范化数据。
import pandas as pd
from sklearn import preprocessing
x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pd.DataFrame(x_scaled)
有关更多信息,请参阅scikit-learn关于预处理数据的文档:将特性扩展到一个范围。