属性错误:“float”对象没有属性“max”

glp*_*psx 2 python function

这是我之前关于使用负值的特定条件标准化 Pandas DataFrame 列的文章的延续。

\n\n

我正在使用的数据框如下:

\n\n
import numpy as np\nimport pandas as pd\n\ndf = pd.DataFrame({\'key\' : [111, 222, 333, 444, 555, 666, 777, 888, 999],\n                   \'score1\' : [-1, 0, 2, -1, 7, 0, 15, 0, 1], \n                   \'score2\' : [2, 2, -1, 10, 0, 5, -1, 1, 0]})\n\nprint(df)\n\n   key  score1  score2\n0  111      -1       2\n1  222       0       2\n2  333       2      -1\n3  444      -1      10\n4  555       7       0\n5  666       0       5\n6  777      15      -1\n7  888       0       1\n8  999       1       0\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
    \n
  • 如果值等于-1,则返回缺失NaN
  • \n
  • 0否则,将剩余正整数标准化为和之间的范围1
  • \n
\n\n

我对ezrael解决方案非常满意。话虽这么说,我继续解决我的问题,看看是否能想出替代解决方案。这是我的尝试:

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

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

\n\n

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

\n\n

我还进行了快速测试,将第二个 \xc2\xb4return\xc2\xb4 语句替换为return x/1515是系列的最大值score1),并且它有效:

\n\n
   key  score1  score2     norm1\n0  111    -1.0       2       NaN\n1  222     0.0       2  0.000000\n2  333     2.0      -1  0.133333\n3  444    -1.0      10       NaN\n4  555     7.0       0  0.466667\n5  666     0.0       5  0.000000\n6  777    15.0      -1  1.000000\n7  888     0.0       1  0.000000\n8  999     1.0       0  0.066667\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n

Fab*_*ioL 5

错误的原因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
Run Code Online (Sandbox Code Playgroud)

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

df['norm1'] = df['score1'].apply(lambda x: normalize(x, df['score1'].max()))
Run Code Online (Sandbox Code Playgroud)