I want to assign labels 0/1 to pandas datafrmae according to columns

徘徊边缘 提交于 2021-02-10 16:57:20

问题


I am fairly new to python.I am trying to assign labels in a pandas dataframe.This is how my dataframe looks : final.head(3)

Match Team1 Team2 winner       
A       2     3      3             
B       1     2      1            
C       3     1      1   

I want to create a new column which demonstrates who won the match.As in if Team1 wins the game label should be 0 and if Team2 wins the game label should be 1. Expected outcome should be : -

Match Team1 Team2 winner label      
A       2     3      3     1        
B       1     2      1     0       
C       3     1      1     1       

Please tell me how should i proceed.Thanks in advance.


回答1:


Your label is essentially whether winner is the same with Team2. So you can do

final['label'] = final['winner'].eq(final['Team2']).astype(int)

Or if you insisted on numpy, then according to your logic:

final['label'] = np.where(final['Team1'].eq(final['winner']), 0, 1)



回答2:


you can do it like this also using where

df["label"] = np.where(df["winner"]==df["Team1"], 0, 1)



回答3:


df.loc[(conditional), 'column_name'] = 'value'

So for you:

final.loc[(df['Team1']>df['Team2']), 'label'] = 'Team1 Won'


来源:https://stackoverflow.com/questions/58137731/i-want-to-assign-labels-0-1-to-pandas-datafrmae-according-to-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!