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

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)

使用Pandas的一个简单方法:(这里我想使用均值归一化)

normalized_df=(df-df.mean())/df.std()

使用最小-最大归一化:

normalized_df=(df-df.min())/(df.max()-df.min())

编辑:为了解决一些问题,需要说明Pandas在上面的代码中自动应用列函数。

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。

下面的函数计算Z分数:

def standardization(dataset):
  """ Standardization of numeric fields, where all values will have mean of zero 
  and standard deviation of one. (z-score)

  Args:
    dataset: A `Pandas.Dataframe` 
  """
  dtypes = list(zip(dataset.dtypes.index, map(str, dataset.dtypes)))
  # Normalize numeric columns.
  for column, dtype in dtypes:
      if dtype == 'float32':
          dataset[column] -= dataset[column].mean()
          dataset[column] /= dataset[column].std()
  return dataset

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

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