Python – 用Pandas逐列缩放数字
在机器学习中,缩放数字是一种常见的预处理技术,用于将数据中存在的独立特征标准化为一个固定范围。当应用于Python序列时,例如Pandas系列,缩放的结果是一个新的序列,使你在某一列中的所有数值都在一个范围内。例如,如果范围是( 0 ,1 ),那么该列中的全部数据将只在0,1范围内。
示例:
if the sequence is **[1, 2, 3]**
then the scaled sequence is **[0, 0.5, 1]**
应用:
- 在机器学习中,缩放可以提高各种算法的收敛速度。
- 在机器学习中,你经常会遇到差异巨大的数据集,许多机器学习模型很难在这些数据上表现良好,所以在这种情况下,缩放有助于将数据保持在一个范围内。
注意:我们将在本文中使用Scikit-learn来扩展pandas数据框架。
步骤:
1.在python中导入pandas和sklearn库。
2.调用DataFrame构造函数以返回一个新的DataFrame。
3.创建一个sklearn.preprocessing.MinMaxScaler的实例。
4.调用sklearn.preprocessing.MinMaxScaler.fit_transform(df[[column_name]])来返回第一步的Pandas DataFrame df,并对指定列进行min-max缩放。
例子1 :
一个非常基本的例子,说明MinMax如何
# importing the required libraries
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# creating a dataframe for example
pd_data = pd.DataFrame({
"Item": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Price": [100, 300, 250, 120, 910, 345, 124, 1000, 289, 500]
})
# Creating an instance of the sklearn.preprocessing.MinMaxScaler()
scaler = MinMaxScaler()
# Scaling the Price column of the created dataFrame and storing
# the result in ScaledPrice Column
pd_data[["ScaledPrice"]] = scaler.fit_transform(pd_data[["Price"]])
print(pd_data)
输出 :
示例2 :你也可以一次缩放多个pandas, DataFrame的列,你只需要在MinMaxScaler.fit_transform()函数中传递列名。
# importing the required libraries
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# creating a dataframe for example
pd_data = pd.DataFrame({
"Item": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Price": [100, 300, 250, 120, 910, 345, 124, 1000, 289, 500],
"Weight": [200, 203, 350, 100, 560, 456, 700, 250, 800, 389]
})
# Creating an instance of the sklearn.preprocessing.MinMaxScaler()
scaler = MinMaxScaler()
# Scaling the Price column of the created dataFrame and storing
# the result in ScaledPrice Column
pd_data[["ScaledPrice", "ScaledWeight"]] = scaler.fit_transform(
pd_data[["Price", "Weight"]])
print(pd_data)
输出 :
例子3:默认情况下,MinMaxScaler()类使用的刻度值是(0,1),但你可以根据你的需要将其改为任何你想要的值。
# importing the required libraries
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# creating a dataframe for example
pd_data = pd.DataFrame({
"Item": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"Price": [100, 300, 250, 120, 910, 345, 124, 1000, 289, 500]
})
# Creating an instance of the sklearn.preprocessing.MinMaxScaler()
# specifying the min and max value of the scale
scaler = MinMaxScaler(feature_range=(20, 500))
# Scaling the Price column of the created dataFrame
# and storing the result in ScaledPrice Column
pd_data[["ScaledPrice"]] = scaler.fit_transform(pd_data[["Price"]])
print(pd_data)
输出 :