Home > Back-end >  Switching Positions of Elements in Pandas DataFrames Rows
Switching Positions of Elements in Pandas DataFrames Rows

Time:09-27

I have the following function below that:

  • Iterates over each row of my Dataframe
  • In each row I check if the condition is satisfied if gamestatistics['championname'].values[i] > gamestatistics['enemyname'].values[i]
  • Switch the positions of the elements for that row if True

I'm wondering if the below could be made faster somehow, as I expect to run this with very large DataFrames which I imagine would take a long time. This also seems very manual, I think I'm missing a function that could do this much faster.

    def main():
      gamestatistics = pd.read_csv('CvCaggregation.csv')
      for i in range(len(gamestatistics)):
        if gamestatistics['championname'].values[i] > gamestatistics['enemyname'].values[i]:
          print(f"Adjustment at {i}")
          currentChampName = gamestatistics['championname'].values[i]
          currentPosition = gamestatistics['position'].values[i]
          currentEnemy = gamestatistics['enemyname'].values[i]
          CurrentEnemyPosition = gamestatistics['enemyposition'].values[i]
          championWinRate = gamestatistics['championwinrate'].values[i]
          enemyWinRate = gamestatistics['enemywinrate'].values[i]
          gamestatistics.at[i, 'championname'] = currentEnemy
          gamestatistics.at[i, 'enemyname'] = currentChampName
          gamestatistics.at[i, 'position'] = CurrentEnemyPosition
          gamestatistics.at[i, 'enemyposition'] = currentPosition
          gamestatistics.at[i, 'championwinrate'] = enemyWinRate
          gamestatistics.at[i, 'enemywinrate'] = championWinRate
      return gamestatistics

Example Data:

Below evaluates true as Yasuo > Akali:

enter image description here

Therefore we switch the values of the columns to the below, that is, Columns 1&3, 2&4, 5&6 are swapped:

enter image description here

CodePudding user response:

Does this answer you question ? Or give us an example of the csv values please.

import pandas as pd

gamestatistics = pd.read_csv('CvCaggregation.csv')
gamestatistics.update(gamestatistics.loc[
    gamestatistics['championname'] > gamestatistics['enemyname']].rename(
        {
            'championname': 'enemyname',
            'enemyname': 'championname',
            'position': 'enemyposition',
            'enemyposition': 'position',
            'championwinrate': 'enemywinrate',
            'enemywinrate': 'championwinrate',
        },
        axis=1))
  • Related