这是我之前的延续post https://stackoverflow.com/questions/26414913/normalize-columns-of-pandas-data-frame/48651066使用负值的特定条件对 Pandas 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
and score2
系列有-1
以及所有正整数(包括0
)。我的目标是通过以下方式标准化两列:
- 如果该值等于
-1
,然后返回缺失的NaN
value
- 否则,将剩余的正整数标准化为
0
and 1
.
我非常满意solution https://stackoverflow.com/questions/57851077/normalizing-pandas-series-with-condition from ezrael。话虽这么说,我继续解决我的问题,看看是否能想出替代解决方案。这是我的尝试:
- 我定义以下函数:
def normalize(x):
if x == -1:
return np.nan
else:
return x/x.max()
- 我正在创建新的
norm1
将上述函数应用到系列中score1
Series:
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
但这不是一个可行的解决方案。我希望能够除以系列的最大值,而不是对其进行硬编码。WHY我的解决方案不起作用吗?HOW我要修复我的代码吗?