Home > database >  Swapping in dataframe columns between odd and even indices
Swapping in dataframe columns between odd and even indices

Time:11-07

I have a dataframe named 'original' that follows the pattern below:

       game      team
0         1         A
1         1         B
2         2         C
3         2         D
...

What I want to do is, to create a new column where for each game the teams are swapped, that is A for B, B for A, C for D, D for C, etc.

Dataframe is several thousands rows long with few hundreds of unique values, so replacing them manually is not possible.

What I did and it worked is:

even_odd = [1, 2]
temp = original.copy()
temp['turns'] = np.tile(even_odd, len(merge2)//len(original)   1)[:len(original)]
temp = temp .sort_values(by = ['game','turns'], ascending = [True, False]).reset_index(drop=True)

original['opponent'] = temp['opponent']

But I am wondering: is there any native python function that could deal with that? Is there a more pythonic way?

CodePudding user response:

A possible solution, based on the idea of reversing order of team inside each group (g[::-1]):

df['team'] = df.groupby('game')['team'].apply(
    lambda g: g[::-1]).reset_index(drop=True)

Output:

   game team
0     1    B
1     1    A
2     2    D
3     2    C
  • Related