我有一个熊猫的数据框架,其中每一列都有不同的值范围。例如:

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)

当前回答

基于这篇文章:https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range

您可以执行以下操作:

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)
    return result

你不需要一直担心你的价值观是积极的还是消极的。这些值应该很好地分布在0和1之间。

其他回答

你可以在一行中完成

DF_test = DF_test.sub(DF_test.mean(axis=0), axis=1)/DF_test.mean(axis=0)

它取每一列的平均值,然后从每一行中减去它(平均值)(特定列的平均值仅从该行中减去),然后仅除以平均值。最后,我们得到的是规范化的数据集。

你可以简单地使用pandas.DataFrame。Transform1函数如下所示:

df.transform(lambda x: x/x.max())

你可能想让一些列被标准化,而其他的列是不变的,比如一些回归任务,数据标签或分类列是不变的,所以我建议你用这种python的方式(它是@shg和@Cina答案的组合):

features_to_normalize = ['A', 'B', 'C']
# could be ['A','B'] 

df[features_to_normalize] = df[features_to_normalize].apply(lambda x:(x-x.min()) / (x.max()-x.min()))

这是你如何使用列表推导式来做的:

[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]

基于这篇文章:https://stats.stackexchange.com/questions/70801/how-to-normalize-data-to-0-1-range

您可以执行以下操作:

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)
    return result

你不需要一直担心你的价值观是积极的还是消极的。这些值应该很好地分布在0和1之间。