【问题标题】:python pandas standardize column for regressionpython pandas标准化回归列
【发布时间】:2017-04-17 19:52:47
【问题描述】:

我有以下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。

谢谢

【问题讨论】:

    标签: python pandas scale normalize standardized


    【解决方案1】:

    我认为您正在寻找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.        ]]
    

    【讨论】:

    • 有趣!我不知道有这个,让我试试
    • 我在不同的列中收到此错误 DeprecationWarning: Passing 1d arrays as data 在 0.17 中已被弃用,并将在 0.19 中引发 ValueError。如果您的数据具有单个特征,则使用 X.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 X.reshape(1, -1)。
    • 我相信你可以将此方法应用于整个数据框
    • 我已经有很多0/1格式的列了;所以我不打算在整个 df 上使用它
    • 我不相信它会影响已经缩放到您的范围的列
    【解决方案2】:

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

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

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

    缩放后的列会出现负数,因为平均值将归一化为零。

    【讨论】:

    • 谢谢;而预处理中的 scale() 正是这样做的?
    • 是的。如果您愿意,可以使用源代码here
    猜你喜欢
    • 2015-11-13
    • 2018-08-02
    • 2016-04-12
    • 2018-09-13
    • 2021-06-25
    • 2016-02-28
    • 2021-05-05
    • 2020-04-27
    • 1970-01-01
    相关资源
    最近更新 更多