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


在广阔的数据探索领域,标准化(有时也称为特征缩放)作为预处理步骤起着至关重要的作用。它将不同的数据元素转换为统一的范围或尺度,从而实现公平的分析和比较。Python 的优秀库 Pandas 无缝地促进了这一工作。

可以将 Pandas DataFrame 看作是二维的、不断变化的、异构的表格数据数组,精心设计用于简化数据操作。凭借其直观的语法和动态功能,它已成为全球数据爱好者的首选结构。让我们深入探讨可以用来标准化 DataFrame 中数据组件的方法。

算法

在本文中,我们将重点关注在 Pandas DataFrame 中进行数据标准化的以下方法:

a. 利用 sklearn.preprocessing.StandardScaler 的强大功能

b. 利用 pandas.DataFrame.apply 方法和 z-score 的潜力

c. 利用 pandas.DataFrame.subtract 和 pandas.DataFrame.divide 方法的多功能性

d. 探索 pandas.DataFrame.sub 和 pandas.DataFrame.div 方法的深度

语法

在本文中,我们将依赖 pandas 库,它为我们提供了许多操作 DataFrame 的函数。以下是每种方法语法的简要概述:

StandardScaler

scaler = StandardScaler()

`StandardScaler` 是 `sklearn.preprocessing` 模块中的一个类,用于通过移除均值并缩放至单位方差来标准化特征。首先,创建一个 `StandardScaler` 类的实例。

fit_transform()

scaler.fit_transform(X)

`fit_transform()` 方法用于标准化输入数据 `X`。

apply

df.apply(func, axis=0)

`apply()` 是 Pandas DataFrame 的一种方法,用于沿指定轴(行或列)应用函数。`func` 是要应用的函数,`axis` 是应用函数的轴(0 代表列,1 代表行)。

subtract 和 divide

df.subtract(df.mean()).divide(df.std())

此语法通过减去均值 (`df.mean()`) 并除以每列的标准差 (`df.std()`) 来标准化 Pandas DataFrame。

sub 和 div

df.sub(df.mean()).div(df.std())

下面的代码片段演示了执行按元素减法和除法以标准化 Pandas DataFrame 的不同方法。每种方法都使用 sub() 和 div() 方法的不同变体,而不是 subtract() 和 divide()。

这些操作通常用于减去 DataFrame 中每列的均值并除以标准差。

示例

使用 sklearn.preprocessing.StandardScaler

在下面的示例中,我们将:

1. 导入必要的库:来自 sklearn 的 StandardScaler、pandas 和 numpy。

2. 创建一个样本 DataFrame 'df',其中包含一列 'A',包含值 1 到 5。

3. 实例化一个 StandardScaler 对象 'scaler',并使用它通过应用 fit_transform() 方法来规范化列 'A'。

4. 打印更新后的 DataFrame,其中列 'A' 中包含标准化值。

from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np

# Construct a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5]
})

# Initialize a scaler
scaler = StandardScaler()

# Fit and transform the data
df['A'] = scaler.fit_transform(np.array(df['A']).reshape(-1, 1))

print(df)

输出

          A
0 -1.414214
1 -0.707107
2  0.000000
3  0.707107
4  1.414214

使用 pandas.DataFrame.apply 方法和 z-score

在下面的示例中,我们将:

1. 导入 pandas 库并创建一个样本 DataFrame 'df',其中包含一列 'A',包含值 1 到 5。

2. 定义一个函数 'standardize',它接受一列并返回通过减去均值并除以标准差得到的标准化值。

3. 使用 apply() 方法将 'standardize' 函数应用于列 'A'。

4. 打印更新后的 DataFrame,其中列 'A' 中包含标准化值。

import pandas as pd

# Construct a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5]
})

def standardize(column):
    return (column - column.mean()) / column.std()

# Standardize column 'A' using the apply function
df['A'] = df['A'].apply(standardize)

print(df)

输出

          A
0 -1.414214
1 -0.707107
2  0.000000
3  0.707107
4  1.414214

利用 pandas.DataFrame.subtract 和 pandas.DataFrame.divide 方法

在下面的示例中,我们将:

1. 导入 pandas 库并创建一个样本 DataFrame 'df',其中包含一列 'A',包含值 1 到 5。

2. 使用 mean() 和 std() 方法计算列 'A' 的均值和标准差。

3. 使用 subtract() 和 divide() 方法,通过减去均值并除以标准差来标准化列 'A'。

4. 打印更新后的 DataFrame,其中列 'A' 中包含标准化值。

import pandas as pd

# Construct a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5]
})

# Standardize column 'A' using subtract and divide methods
df['A'] = df['A'].subtract(df['A'].mean()).divide(df['A'].std())

print(df)

输出

          A
0 -1.414214
1 -0.707107
2  0.000000
3  0.707107
4  1.414214

利用 pandas.DataFrame.sub 和 pandas.DataFrame.div 方法

在下面的示例中,我们将:

1. 导入 pandas 库并创建一个样本 DataFrame 'df',其中包含一列 'A',包含值 1 到 5。

2. 使用 mean() 和 std() 方法计算列 'A' 的均值和标准差。

3. 使用 sub() 和 div() 方法,通过减去均值并除以标准差来标准化列 'A'。

4. 打印更新后的 DataFrame,其中列 'A' 中包含标准化值。

import pandas as pd

# Construct a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5]
})

# Standardize column 'A' using sub and div methods
df['A'] = df['A'].sub(df['A'].mean()).div(df['A'].std())

print(df)

输出

          A
0 -1.264911
1 -0.632456
2  0.000000
3  0.632456
4  1.264911

结论

总之,鉴于各种机器学习算法对其输入特征的规模敏感,数据标准化在预处理中起着关键作用。选择合适的标准化方法取决于具体的算法和数据的性质。当内容遵循正态分布时,z 分数标准化最合适,而对于未知或非正态分布,最小-最大归一化是合适的选择。但是,在数据相关的工作中做出谨慎的决定需要在选择特定的缩放方法之前深刻理解数据本身。掌握这些方法的基本原理并在 Python 中掌握它们的实现,为在数据探索的启蒙之旅中取得进展奠定了坚实的基础。

更新于:2023年8月28日

3K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.