简体   繁体   中英

Comparing two columns of the dataframe against a new dataframe column

I have two dataframes which looks like

   team  points
0     1     2.5
1     2     3.2
2     5     5.8
3     3     2.8
4     4     1.9

and:

   team1  team2
0      1      5
1      2      4
2      3      1

Expected output should give me a new column with the winner (more points):

team1   team2   winner
 1         5       5
 2         4       2
 3         1       3

here is a way using applymap , df.idxmax() and df.lookup :

s=df2.applymap(df1.set_index('team')['points'].get).idxmax(1)

Or better alternative courtesy @user3483203

s=df2.stack().map(df1.set_index('team')['points']).unstack().idxmax(1)
#s.tolist() gives ['team2', 'team1', 'team1']
df2['winner']=df2.lookup(s.index,s)
print(df2)

   team1  team2  winner
0      1      5       5
1      2      4       2
2      3      1       3

Trying to avoid applymap and use lookup + reshape

x = df.set_index('team').lookup(df2.values.ravel('F'), ["points"]*df2.size)
                        .reshape(df2.shape, order='F')
                        .argmax(1)

df2['winner'] = df2.lookup(df2.index, df2.columns[x])

   team1  team2  winner
0      1      5       5
1      2      4       2
2      3      1       3

Alternative solution only using pandas.Series.map , DataFrame.stack and DataFrame.unstack :

df_match['winner']=( df_match.stack()
                             .map(df.set_index('team')['points'])
                             .unstack()
                             .max(axis=1)
                             .map(df.set_index('points')['team']) )

print(df_match)

   team1  team2  winner
0      1      5       5
1      2      4       2
2      3      1       3

My "simple" solution:

df3= df2.replace(df1.set_index("team").points.to_dict()) 
df2["winner"]= np.where(df3.team1>=df3.team2,df2.team1,df2.team2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM