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

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)

当前回答

def normalize(x):
    try:
        x = x/np.linalg.norm(x,ord=1)
        return x
    except :
        raise
data = pd.DataFrame.apply(data,normalize)

根据pandas的文档,DataFrame结构可以对自身应用操作(函数)。

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

沿着数据帧的输入轴应用函数。 传递给函数的对象是具有DataFrame的索引(轴=0)或列(轴=1)索引的Series对象。返回类型取决于传递的函数是否聚合,如果DataFrame为空则使用reduce参数。

您可以应用自定义函数来操作DataFrame。

其他回答

如果你的数据是正倾斜的,最好的归一化方法是使用对数变换:

df = np.log10(df)

你可以在一行中完成

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

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

嘿,使用带有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))

正常化

您可以使用minmax_scale将每一列转换为从0到1的刻度。

from sklearn.preprocessing import minmax_scale
df[:] = minmax_scale(df)

标准化

您可以使用比例将每列居中到平均值,并缩放到单位方差。

from sklearn.preprocessing import scale
df[:] = scale(df)

列的子集

归一化单列

from sklearn.preprocessing import minmax_scale
df['a'] = minmax_scale(df['a'])

只归一化数值列

import numpy as np
from sklearn.preprocessing import minmax_scale
cols = df.select_dtypes(np.number).columns
df[cols] = minmax_scale(df[cols])

完整的示例

# Prep
import pandas as pd
import numpy as np
from sklearn.preprocessing import minmax_scale

# Sample data
df = pd.DataFrame({'a':[0,1,2], 'b':[-10,-30,-50], 'c':['x', 'y', 'z']})

# MinMax normalize all numeric columns
cols = df.select_dtypes(np.number).columns
df[cols] = minmax_scale(df[cols])

# Result
print(df)

#    a    b  c
# 0  0.0  1.0  x
# 2  0.5  0.5  y
# 3  1.0  0.0  z

注:

在所有示例中,可以使用scale来代替minmax_scale。保持索引、列名或非数值变量不变。函数应用于每一列。

警告:

对于机器学习,可以使用minmax_scale或train_test_split后的scale来避免数据泄露。

Info

更多关于标准化和规范化的信息:

https://machinelearningmastery.com/standardscaler-and-minmaxscaler-transforms-in-python/ https://en.wikipedia.org/wiki/Normalization_(统计) https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing

你可能想让一些列被标准化,而其他的列是不变的,比如一些回归任务,数据标签或分类列是不变的,所以我建议你用这种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()))