我刚刚开始使用 Python 和机器学习,遇到了一个我无法自行解决或无法使用任何其他在线资源解决的问题。 我正在尝试按以下方式使用 lambda 函数缩放 pandas 数据框中的列:
X['col1'] = X['col1'].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
并得到以下错误信息:
'float' object has no attribute 'min'
我尝试将数据类型转换为整数,但返回了以下错误:
'int' object has no attribute 'min'
我相信我犯了一些非常基本的错误,希望任何人都能指出正确的方向。
最佳答案
我认为没有必要在此处应用,因为存在更快的矢量化解决方案 - 将 x
更改为 X['col1']
列:
X = pd.DataFrame({'col1': [100,10,1,20,10,-20,200]})
X['col2'] = (X['col1'] - X['col1'].min()) / (X['col1'].max() - X['col1'].min())
print (X)
col1 col2
0 100 0.545455
1 10 0.136364
2 1 0.095455
3 20 0.181818
4 10 0.136364
5 -20 0.000000
6 200 1.000000
就像@meW 在评论中指出的那样,另一个解决方案是使用 MinMaxScaler
:
from sklearn import preprocessing
min_max_scaler = preprocessing.MinMaxScaler()
X['col2'] = min_max_scaler.fit_transform(X[['col1']])
print (X)
col1 col2
0 100 0.545455
1 10 0.136364
2 1 0.095455
3 20 0.181818
4 10 0.136364
5 -20 0.000000
6 200 1.000000
关于python - 用于缩放 pandas 数据框中的列的 lambda 函数返回 : "' float' object has no attribute 'min' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54086977/