Python:使用pandas逐列缩放数字

Rod*_*phe 29 python pandas

我有一个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
Run Code Online (Sandbox Code Playgroud)

Zel*_*ny7 55

这是你如何使用sklearnpreprocessing模块.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
Run Code Online (Sandbox Code Playgroud)

  • 如果不编写流水线,使用 [`minmax_scale(df)`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.minmax_scale.html) 而不是 `MinMaxScaler` 更简单。 (3认同)

And*_*den 30

您可以减去最小值,然后除以最大值(当心0/0).请注意,减去min后,新的max是原始的max - min.

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
Run Code Online (Sandbox Code Playgroud)

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

In [15]: df['b'] = 1 - df['b']
Run Code Online (Sandbox Code Playgroud)

另一种方法是否定B柱第一(df['b'] = -df['b']).


Yeh*_*ter 14

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

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
df['Col1_scaled'] = scaler.fit_transform(df['Col1'].values.reshape(-1,1))
Run Code Online (Sandbox Code Playgroud)


Fal*_*on9 7

这不是很优雅,但以下适用于这两个案例:

#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']
Run Code Online (Sandbox Code Playgroud)

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