2017-04-10 59 views
1

假设有数据帧与以下数据Python - 基于另一列中的值获取两个colums的最大值还是最小值?

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 

什么是查找分钟的最短途径[score1,score2]如果计数== 0或MAX [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 

回答

2

Excel的IF函数的等效阵列我s 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 
0

为什么你需要额外的值存储在行?

data['fin_score'] = (max if data['count'] else min)(map(lambda k: data['score' + k], ('1', '2'))) 
相关问题