Home > Enterprise >  Pandas - add row with inverted values based on condition
Pandas - add row with inverted values based on condition

Time:11-13

In a dataframe like this:

...
      match     team         opponent venue  
233   3b0345fb  Brazil     Argentina  Home       
234   3b2357fb  Argentina     Brazil  Away       
427   3b0947fb  England       Poland  Home           
...

how can I select one dataframe slice, based on a column value (df[df['team']=='England']), like this:

...
        match   team    opponent venue  
559   4a3eae2f  England  Poland  Home  
...

And add inverted rows of that slice to the original dataframe, changing 'Home' with 'Away', ending up with:

...
      match     team        opponent venue  
233   3b0345fb  Brazil     Argentina  Home       
234   3b2357fb  Argentina     Brazil  Away       
559   3b0947fb  England      Poland   Home 
560   3b0947fb  Poland      England   Away                    
...

Note: This slice should contain n rows and produce n inverted rows.

CodePudding user response:

You can use:

df2 = df[df['team'].eq('England')].copy()
df2[['team', 'opponent']] = df2[['opponent', 'team']]
df2['venue'] = df2['venue'].map({'Home': 'Away', 'Away': 'Home})

out = pd.concat([df, df2])
print(out)

Output:

        match       team   opponent venue
233  3b0345fb     Brazil  Argentina  Home
234  3b2357fb  Argentina     Brazil  Away
427  3b0947fb    England     Poland  Home
427  3b0947fb     Poland    England  Away

If you want to invert all:

df2 = df.copy()
df2[['team', 'opponent']] = df2[['opponent', 'team']]
df2['venue'] = df2['venue'].map({'Home': 'Away', 'Away': 'Home})

out = pd.concat([df, df2])

output:

        match       team   opponent venue
233  3b0345fb     Brazil  Argentina  Home
234  3b2357fb  Argentina     Brazil  Away
427  3b0947fb    England     Poland  Home
233  3b0345fb  Argentina     Brazil  Away
234  3b2357fb     Brazil  Argentina  Home
427  3b0947fb     Poland    England  Away
  • Related