I am just getting started in Python and Machine Learning and have encountered an issue which I haven’t been able to fix myself or with any other online resource. I am trying to scale a column in a pandas dataframe using a lambda function in the following way:
JavaScript
x
2
1
X['col1'] = X['col1'].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
2
and get the following error message:
‘float’ object has no attribute ‘min’
I have tried to convert the data type into integer and the following error is returned:
‘int’ object has no attribute ‘min’
I believe I am getting something pretty basic wrong, hope anyone can point me in the right direction.
Advertisement
Answer
I think apply here is not necessary, because exist faster vectorized solution – change x
to column X['col1']
:
JavaScript
1
13
13
1
X = pd.DataFrame({'col1': [100,10,1,20,10,-20,200]})
2
X['col2'] = (X['col1'] - X['col1'].min()) / (X['col1'].max() - X['col1'].min())
3
print (X)
4
5
col1 col2
6
0 100 0.545455
7
1 10 0.136364
8
2 1 0.095455
9
3 20 0.181818
10
4 10 0.136364
11
5 -20 0.000000
12
6 200 1.000000
13
Like @meW pointed in comments another solution is use MinMaxScaler
:
JavaScript
1
15
15
1
from sklearn import preprocessing
2
3
min_max_scaler = preprocessing.MinMaxScaler()
4
X['col2'] = min_max_scaler.fit_transform(X[['col1']])
5
print (X)
6
7
col1 col2
8
0 100 0.545455
9
1 10 0.136364
10
2 1 0.095455
11
3 20 0.181818
12
4 10 0.136364
13
5 -20 0.000000
14
6 200 1.000000
15