这是我之前关于使用负值的特定条件标准化 Pandas DataFrame 列的文章的延续。
\n\n我正在使用的数据框如下:
\n\nimport 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\nRun Code Online (Sandbox Code Playgroud)\n\nscore1和score2Series的可能值为-1和 所有正整数(包括0)。我的目标是通过以下方式标准化两列:
-1,则返回缺失NaN值0否则,将剩余正整数标准化为和之间的范围1。我对ezrael的解决方案非常满意。话虽这么说,我继续解决我的问题,看看是否能想出替代解决方案。这是我的尝试:
\n\ndef normalize(x):\n if x == -1:\n return np.nan\n else:\n return x/x.max()\nRun Code Online (Sandbox Code Playgroud)\n\nnorm1通过将上述函数应用于score1系列来创建新系列:df[\'norm1\'] = df[\'score1\'].apply(normalize)\nRun Code Online (Sandbox Code Playgroud)\n\n不幸的是,这引发了以下问题AttributeError: \'int\' object has no attribute \'max\'。
我将score1系列转换为float64但它不能解决问题:\'float\' object has no attribute \'max\'。
我还进行了快速测试,将第二个 \xc2\xb4return\xc2\xb4 语句替换为return x/15(15是系列的最大值score1),并且它有效:
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\nRun Code Online (Sandbox Code Playgroud)\n\n但这不是一个可行的解决方案。我希望能够除以系列的最大值,而不是对其进行硬编码。为什么我的解决方案不起作用以及如何修复我的代码?
\n错误的原因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)
| 归档时间: |
|
| 查看次数: |
11543 次 |
| 最近记录: |