简体   繁体   中英

How to create a new column based on matching ID's and string's in names of other columns in the same data frame?

I have tried to find a solution online but I cannot. I have a dataframe with 10 separate id columns, and 10 separate corresponding value columns for each ID. A brief example is shown below

Example:

player_id_1    player_1_x   player_id_2   player_2_x  shooter_id 

300               10           301           12           301

299               11           300           13           299

I want to create a new column that takes the value column from the corresponding match of ID's between the 'shooter_id' and any of the 'player_id' columns like below:

player_id_1    player_1_x   player_id_2   player_2_x  shooter_id  shooter_x

300               10           301           12           301         12 

299               11           300           13           299         11

I have really been struggling to make this work, I am not sure if I need to merge within itself, for loop through the dataframe, or.apply.. any insight would be very helpful!

Thank you!

Let's filter the player_id like columns, the use .eq + idxmax to get the player_id columns where the match is found, finally use lookup to get values corresponding to player_id's :

c = df.filter(like='player_id')\
      .eq(df['shooter_id'], axis=0)\
      .idxmax(1).str.replace('_id', '').add('_x')

df['shooter_x'] = df.lookup(df.index, c)

   player_id_1  player_1_x  player_id_2  player_2_x  shooter_id  shooter_x
0          300          10          301          12         301         12
1          299          11          300          13         299         11

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