假设数据框包含以下数据
key score1 score2 count
1 0.87 0.13 0
2 0.67 0.33 1
3 0.46 0.54 1
4 0.28 0.72 0
5 0.41 0.59 1
如果count == 0或者当count> gt时,如果count == 0或max [score1,score2],找到min [score1,score2]的最短方法是什么? 0?
目前解决方案有
data['mini']=data[[score1, score2]].min(axis=1)
data['maxi']=data[[score1, score2]].max(axis=1)
data['fin_score']= data['mini'].where(data['count']==0, data['maxi'])
是否可以使其变得更加清晰(在1/2命令中),就像在Excel中一样,这将如下所示,然后只是在所有行中拖动公式
=IF(count>0,MAX(B2:C2),MIN(B2:C2))
结果会喜欢这个
key score1 score2 count fin_score
1 0.87 0.13 0 0.13
2 0.67 0.33 1 0.67
3 0.46 0.54 1 0.54
4 0.28 0.72 0 0.28
5 0.41 0.59 1 0.59
答案 0 :(得分:2)
Excel的IF函数等效数组是np.where
:
df['fin_score'] = np.where(df['count']==0, df[['score1', 'score2']].min(axis=1), df[['score1', 'score2']].max(axis=1))
df
Out:
key score1 score2 count fin_score
0 1 0.87 0.13 0 0.13
1 2 0.67 0.33 1 0.67
2 3 0.46 0.54 1 0.54
3 4 0.28 0.72 0 0.28
4 5 0.41 0.59 1 0.59
答案 1 :(得分:0)
为什么需要存储在行中的额外值?
data['fin_score'] = (max if data['count'] else min)(map(lambda k: data['score' + k], ('1', '2')))