首页 > 解决方案 > AttributeError:“float”对象没有属性“max”

问题描述

这是我之前关于使用负值特定条件规范化 Pandas DataFrame 列的帖子的延续。

我使用的 DataFrame 如下:

import numpy as np
import pandas as pd

df = pd.DataFrame({'key' : [111, 222, 333, 444, 555, 666, 777, 888, 999],
                   'score1' : [-1, 0, 2, -1, 7, 0, 15, 0, 1], 
                   'score2' : [2, 2, -1, 10, 0, 5, -1, 1, 0]})

print(df)

   key  score1  score2
0  111      -1       2
1  222       0       2
2  333       2      -1
3  444      -1      10
4  555       7       0
5  666       0       5
6  777      15      -1
7  888       0       1
8  999       1       0

score1score2Series的可能值是-1所有正整数(包括0)。我的目标是通过以下方式对两列进行规范化:

我对 ezrael 的解决方案非常满意。话虽如此,我继续解决我的问题,看看是否可以提出替代解决方案。这是我的尝试:

  1. 我正在定义以下功能:
def normalize(x):
    if x == -1:
        return np.nan
    else:
        return x/x.max()
  1. norm1通过将上述函数应用于系列来创建新score1系列:
df['norm1'] = df['score1'].apply(normalize)

不幸的是,这引发了以下问题AttributeError: 'int' object has no attribute 'max'

我将score1系列转换为float64但它不能解决问题:'float' object has no attribute 'max'.

我还通过将第二个“return”语句替换为return x/1515是系列的最大值score1)进行了快速测试,它起作用了:

   key  score1  score2     norm1
0  111    -1.0       2       NaN
1  222     0.0       2  0.000000
2  333     2.0      -1  0.133333
3  444    -1.0      10       NaN
4  555     7.0       0  0.466667
5  666     0.0       5  0.000000
6  777    15.0      -1  1.000000
7  888     0.0       1  0.000000
8  999     1.0       0  0.066667

但这不是一个可行的解决方案。我希望能够除以 Series 的最大值,而不是对其进行硬编码。为什么我的解决方案不起作用,我该如何修复我的代码?

标签: pythonfunction

解决方案


错误的原因AttributeError: 'float' object has no attribute 'max'是您的代码在列的每个(浮动)项上调用 max() 函数,您可以将列的最大值传递给normalize函数:

def normalize(x, col_max):
    if x == -1:
        return np.nan
    else:
        return x/col_max

并编辑 norm1 列创建代码如下:

df['norm1'] = df['score1'].apply(lambda x: normalize(x, df['score1'].max()))

推荐阅读