where创建具有三个条件的新列

where创建具有三个条件的新列

本文介绍了使用np.where创建具有三个条件的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在np.where()中获得三个条件.通常它只使用两个条件,我怎么才能得到三个.就像我需要创建一个新列Better_Event来存储夏季",冬季"或两者",基于使用"np"在夏季和冬季比赛中获得的总奖牌数之间的比较(即,Total_Summer和Total_Winter列之间的比较) .where()"功能.

how can I get three conditions in np.where(). normally it uses only two conditions how can I get three.Like I need to Create a new column Better_Event that stores 'Summer' ,'Winter' or 'Both' based on the comparision between the total medals won in Summer event and Winter event (i.e. comparision between the Total_Summer and Total_Winter columns) using "np.where()"function.

data['Better_Events'] = np.where(data['Total_Summer']>data['Total_Winter'],'Summer','Winter')

上面的代码只有两个输出.我如何将其更改为三个,如果data ['Total_Summer'] == data ['Total_Winter']给出两者"

the above code only has two output . how do I change it to three where ifdata['Total_Summer']==data['Total_Winter'] gives "Both"

推荐答案

您需要 np.select :

以下是示例:

df=pd.DataFrame({'Total_Summer':[1,2,3,3,6,7],'Total_Winter':[2,2,3,4,5,4]})
print(df)


   Total_Summer  Total_Winter
0             1             2
1             2             2
2             3             3
3             3             4
4             6             5
5             7             4


现在设置条件和每个条件的值:

cond=[df['Total_Summer']>df['Total_Winter'],df['Total_Summer']<df['Total_Winter'],df['Total_Summer'].eq(df['Total_Winter'])]
values=['Summer','Winter','Both']
df['Better_Events']=np.select(cond,values)
print(df)


   Total_Summer  Total_Winter Better_Events
0             1             2        Winter
1             2             2          Both
2             3             3          Both
3             3             4        Winter
4             6             5        Summer
5             7             4        Summer

这篇关于使用np.where创建具有三个条件的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 14:08