python - 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
score1
和score2
Series的可能值是-1
所有正整数(包括0
)。我的目标是通过以下方式对两列进行规范化:
- 如果值等于
-1
,则返回缺失NaN
值 0
否则,在和之间的范围内对剩余的正整数进行归一化1
。
我对 ezrael 的解决方案非常满意。话虽如此,我继续解决我的问题,看看是否可以提出替代解决方案。这是我的尝试:
- 我正在定义以下功能:
def normalize(x):
if x == -1:
return np.nan
else:
return x/x.max()
- 我
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/15
(15
是系列的最大值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 的最大值,而不是对其进行硬编码。为什么我的解决方案不起作用,我该如何修复我的代码?
解决方案
错误的原因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()))
推荐阅读
- c++ - C++ 标准中的栅栏定义 [n4713 中的 atomics.fences]
- java - Spring MVC - 使用 outputstream 和 HttpServletResponse 下载 PDF
- sql - 文本中点或逗号后可能有数字的数字的正则表达式
- linux - 使用 dbus 保持启动画面直到 X Server 准备就绪
- django - Django-select2 不显示模型数据
- android - 尽管有 ProgressBar,但 FloatingActionButton 可见
- php - 使用 PHP 的 Flask 应用程序的登录模块
- c# - EF Core 在迁移时将列数据从表移动到另一个表 (UP)
- python - Tensorflow初始化一个只有一行/列不为零的稀疏张量?
- android - 无法构建 Xamarin.Android,因为 Xamarin 找不到“aapt.exe”