📜  如何标准化 Pandas DataFrame 中的数据?

📅  最后修改于: 2022-05-13 01:54:32.896000             🧑  作者: Mango

如何标准化 Pandas DataFrame 中的数据?

在本文中,我们将学习如何标准化 Pandas Dataframe 中的数据。

标准化是特征缩放中一个非常重要的概念,它是特征工程的一个组成部分。当您为数据分析或机器学习收集数据时,我们将拥有很多特征,它们是独立的特征。在独立特征的帮助下,我们将尝试预测监督学习中的依赖特征。在查看数据时,如果您看到数据中会有更多的噪音,这将使模型面临受到异常值影响的风险。因此,为此,我们通常会对数据进行规范化或标准化。现在让我们进一步讨论标准化的话题。

这是缩小数据规模并使机器学习模型更容易从中学习的另一个过程。在这种方法中,我们将尝试将均值降低到“0”,将标准差降低到“1”。

您必须知道的另一件重要事情是,当您对数据进行规范化时,值将缩小到从 0 到 1 的特定范围。在标准化中,数据没有特定的边界可以缩小到。

方法1:在pandas中实现[Z-Score]

为了标准化 pandas 中的数据,Z-Score 是 pandas 中一种非常流行的方法,用于对数据进行标准化。 Z-Score 将告诉我们一个值与平均值相差多少标准差。当我们对数据进行标准化时,数据将变为特定形式,其频率图将形成钟形曲线。转换数据的公式是,

句法:

在这种方法中,我们将使用 pandas 内置函数 mean() 和 std() 对数据集的第一列进行标准化,这将给出列数据的均值和标准差。因此,使用简单的计算减去元素的平均值并将它们除以标准偏差将为我们提供数据的 z 分数,即标准化数据。

使用中的数据框:

示例:标准化数据

Python3
# Importing the library
import pandas as pd
  
# Creating the data frame
details = {
    'col1': [1, 3, 5, 7, 9],
    'col2': [7, 4, 35, 14, 56]
}
  
# creating a Dataframe object
df = pd.DataFrame(details)
  
# Z-Score using pandas
df['col1'] = (df['col1'] - df['col1'].mean()) / df['col1'].std()


Python
# Importing the library
import pandas as pd
import scipy
from scipy import stats
  
  
# Creating the data frame
details = {
    'col1': [1, 3, 5, 7, 9],
    'col2': [7, 4, 35, 14, 56]
}
  
# creating a Dataframe object
df = pd.DataFrame(details)
  
# Z-Score using scipy
df['col2'] = stats.zscore(df['col2'])


Python
# Importing the library
import pandas as pd
from sklearn.preprocessing import StandardScaler
  
  
# Creating the data frame
details = {
    'col1': [1, 3, 5, 7, 9],
    'col2': [7, 4, 35, 14, 56]
}
  
# creating a Dataframe object
df = pd.DataFrame(details)
  
# define standard scaler
scaler = StandardScaler()
  
# transform data
df = scaler.fit_transform(df)


输出:

方法 2:使用 scipy.stats()

Scipy 是一个科学计算库。它可以单枪匹马地处理任何复杂的数学计算。像每个计算一样,scipy 也可以处理统计计算,因此我们只需一行代码就可以找到任何列的 z 分数。

句法:

现在我们将通过使用 scipy.stats.zscore() 查找 z 分数来标准化数据的第二列,我们只需要提及该列,库将处理所有事情。

示例:标准化值

Python

# Importing the library
import pandas as pd
import scipy
from scipy import stats
  
  
# Creating the data frame
details = {
    'col1': [1, 3, 5, 7, 9],
    'col2': [7, 4, 35, 14, 56]
}
  
# creating a Dataframe object
df = pd.DataFrame(details)
  
# Z-Score using scipy
df['col2'] = stats.zscore(df['col2'])

输出:

方法3:使用sci-kit learn Standard scaler

Sci-kit Earn 是一个机器学习和模型构建库。我们可以在这个库中执行许多操作,如预处理、分析,以及为各种机器学习(如监督和无监督学习问题)建立模型。在这个库中,一个名为standardscaler() 的预处理方法用于标准化数据。

句法:

在这个例子中,我们将把整个数据转换成一个标准化的形式。为此,我们首先需要创建一个 standardscaler() 对象,然后拟合和转换数据。

示例:标准化值

Python

# Importing the library
import pandas as pd
from sklearn.preprocessing import StandardScaler
  
  
# Creating the data frame
details = {
    'col1': [1, 3, 5, 7, 9],
    'col2': [7, 4, 35, 14, 56]
}
  
# creating a Dataframe object
df = pd.DataFrame(details)
  
# define standard scaler
scaler = StandardScaler()
  
# transform data
df = scaler.fit_transform(df)

输出: