【问题标题】:Python: Scaling numbers column by column with pandasPython:使用熊猫逐列缩放数字
【发布时间】:2014-03-12 22:27:10
【问题描述】:

我有一个 Pandas 数据框“df”,我想在其中逐列执行一些缩放。

  • 在“a”列中,我需要最大数字为 1,最小数字为 0,其他所有数字都相应地展开。
  • 但是,在“b”列中,我需要最小数字为 1,最大数字为 0,并且所有其他值都相应地分布。

是否有执行这两个操作的 Pandas 函数?如果没有,numpy 肯定会这样做。

    a    b
A   14   103
B   90   107
C   90   110
D   96   114
E   91   114

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这就是使用sklearn 和preprocessing 模块的方法。 Sci-Kit Learn 具有许多用于缩放和居中数据的预处理功能。

    In [0]: from sklearn.preprocessing import MinMaxScaler
    
    In [1]: df = pd.DataFrame({'A':[14,90,90,96,91],
                               'B':[103,107,110,114,114]}).astype(float)
    
    In [2]: df
    Out[2]:
        A    B
    0  14  103
    1  90  107
    2  90  110
    3  96  114
    4  91  114
    
    In [3]: scaler = MinMaxScaler()
    
    In [4]: df_scaled = pd.DataFrame(scaler.fit_transform(df), columns=df.columns)
    
    In [5]: df_scaled
    Out[5]:
              A         B
    0  0.000000  0.000000
    1  0.926829  0.363636
    2  0.926829  0.636364
    3  1.000000  1.000000
    4  0.939024  1.000000
    

    【讨论】:

    【解决方案2】:

    您可以减去最小值,然后除以最大值(注意 0/0)。注意减去最小值后,新的最大值就是原来的最大值-最小值。

    In [11]: df
    Out[11]:
        a    b
    A  14  103
    B  90  107
    C  90  110
    D  96  114
    E  91  114
    
    In [12]: df -= df.min()  # equivalent to df = df - df.min()
    
    In [13]: df /= df.max()  # equivalent to df = df / df.max()
    
    In [14]: df
    Out[14]:
              a         b
    A  0.000000  0.000000
    B  0.926829  0.363636
    C  0.926829  0.636364
    D  1.000000  1.000000
    E  0.939024  1.000000
    

    要切换列的顺序(从 1 到 0,而不是从 0 到 1):

    In [15]: df['b'] = 1 - df['b']
    

    另一种方法是否定 b 列 first (df['b'] = -df['b'])。

    【讨论】:

    • 不过,您需要将1- 换成b。
    • 您需要弄乱b 列才能得到翻转。我会说乘以 -1,应用 sub 和 div,然后再乘以 -1。
    • @TomAugspurger 其实我觉得翻转更优雅,你只需要在之前做! :)
    【解决方案3】:

    如果您只想缩放数据框中的一列,可以执行以下操作:

    from sklearn.preprocessing import MinMaxScaler
    
    scaler = MinMaxScaler()
    df['Col1_scaled'] = scaler.fit_transform(df['Col1'].values.reshape(-1,1))
    

    【讨论】:

      【解决方案4】:

      这不是很优雅,但以下适用于这两个列的情况:

      #Create dataframe
      df = pd.DataFrame({'A':[14,90,90,96,91], 'B':[103,107,110,114,114]})
      
      #Apply operates on each row or column with the lambda function
      #axis = 0 -> act on columns, axis = 1 act on rows
      #x is a variable for the whole row or column
      #This line will scale minimum = 0 and maximum = 1 for each column
      df2 = df.apply(lambda x:(x.astype(float) - min(x))/(max(x)-min(x)), axis = 0)
      
      #Want to now invert the order on column 'B'
      #Use apply function again, reverse numbers in column, select column 'B' only and 
      #reassign to column 'B' of original dataframe
      df2['B'] = df2.apply(lambda x: 1-x, axis = 1)['B']
      

      如果我找到一种更优雅的方式(例如,使用列索引:(0 或 1)mod 2 - 1 来选择应用操作中的符号,这样只需一个应用命令即可完成,我会让你知道。

      【讨论】:

        【解决方案5】:

        我认为this 答案中的Acumenus' 评论应该明确提及作为答案,因为它是单行的。

        >>> import pandas as pd
        >>> from sklearn.preprocessing import minmax_scale
        >>> df = pd.DataFrame({'A':[14,90,90,96,91], 'B':[103,107,110,114,114]})
        >>> minmax_scale(df)
        array([[0.        , 0.        ],
               [0.92682927, 0.36363636],
               [0.92682927, 0.63636364],
               [1.        , 1.        ],
               [0.93902439, 1.        ]])
        

        【讨论】:

          【解决方案6】:

          给定一个数据框

          df = pd.DataFrame({'A':[14,90,90,96,91], 'B':[103,107,110,114,114]})
          

          均值为 0 和 var 1 的尺度

          df.apply(lambda x: (x - np.mean(x)) / np.std(x), axis=0)
          

          范围在 0 到 1 之间的刻度

          df.apply(lambda x: x / np.max(x), axis=0)
          

          【讨论】:

          • 答案在 0 和 1 之间缩放的公式没有考虑最小值。另外,如果 max 为 0 怎么办?
          猜你喜欢
          • 1970-01-01
          • 2018-10-06
          • 2020-03-09
          • 2021-08-30
          • 2021-06-15
          • 2022-11-14
          • 2014-01-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多