问题
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