2

我有以下df:

Date       Event_Counts   Category_A  Category_B
20170401      982457          0           1
20170402      982754          1           0
20170402      875786          0           1

我正在为回归分析准备数据,并希望将 Event_Counts 列标准化,使其与类别具有相似的规模。

我使用以下代码:

from sklearn import preprocessing
df['scaled_event_counts'] = preprocessing.scale(df['Event_Counts'])

虽然我确实收到了这个警告:

DataConversionWarning: Data with input dtype int64 was converted to float64 by the scale function.
  warnings.warn(msg, _DataConversionWarning)

它似乎奏效了;有一个新列。但是,它有负数,例如 -1.3

我认为 scale 函数的作用是从数字中减去平均值,然后除以每行的标准差;然后将结果的最小值添加到每一行。

这样对熊猫不起作用吗?或者我应该使用 normalize() 函数还是 StandardScaler() 函数?我希望标准化列的范围为 0 到 1。

谢谢你

4

2 回答 2

5

我想你正在寻找sklearn.preprocessing.MinMaxScaler. 这将允许您扩展到给定范围。

因此,在您的情况下,它将是:

scaler = preprocessing.MinMaxScaler(feature_range=(0,1))
df['scaled_event_counts'] = scaler.fit_transform(df['Event_Counts'])

要缩放整个 df:

scaled_df = scaler.fit_transform(df)
print(scaled_df)
[[ 0.          0.99722347  0.          1.        ]
 [ 1.          1.          1.          0.        ]
 [ 1.          0.          0.          1.        ]]
于 2017-04-17T20:05:25.607 回答
1

缩放是通过减去平均值并除以每个特征(列)的标准差来完成的。所以,

scaled_event_counts = (Event_Counts - mean(Event_Counts)) / std(Event_Counts)

int64 到 float64 警告来自必须减去平均值,平均值是浮点数,而不仅仅是整数。

由于平均值将归一化为零,因此缩放列将具有负数。

于 2017-04-17T20:05:13.233 回答