Search code examples
python-3.xpandasdataframegame-engine

How do I replicate rows a specific number of times according to a condition?


I'm trying to create a dataframe for a game simulation to calculate how many points each player would make according to a set of parameters.

I have this dataframe:

  PLAYER TYPE  Quantity in my base  STRENGTH  POWER  Number of Matches (min)  \
0           A                    2        15    200                        3   
1           B                    3        80     20                        0   

   Number of Matches (max)  
0                        5  
1                        2  

df

Each row in this df represents one type of player. On column "Quantity in my base" I have the number of times each type of player appears in my base and on columns "Number of Matches" the minimum and maximum number of matches they each type of player is expected to play in one day.

I need to replicate the rows for each type of players with their respective "Strength" and "Power" a number of times that is = to "Quantity in my base" times a random number between the min and max number of matches of each one. I'm doing this so that, on the new data frame, each row will represent one match per each specific player in my base.

For instance. If

    PLAYERTYPE Quantity_in_my_base Rand_Num_Matches Number_of_rows
0   A1  2   4   8
1   A2  3   3   9

Number of rows to be replicated

Than I want to create a second df like this:

PLAYERTYPE STRENGTH POWER
0   A   15  200
1   A   15  200
2   A   15  200
3   A   15  200
4   A   15  200
5   A   15  200
6   A   15  200
7   A   15  200
8   A   15  200
9   A   15  200
10  A   15  200
11  A   15  200
12  A   15  200
13  A   15  200
14  A   15  200
15  A   15  200
16  A   15  200

New df

But I want to do this for players A1, A2 and B1, B2, B3 and so on, in a way that each one will be replicating according to their respective random number.

Thank you so much!


Solution

  • You could use .repeat() ;

    repeat_df = df.loc[df.index.repeat(df['Number of Matches'])]
    repeat_df[['PLAYERTYPE', 'STRENGTH', 'POWER']]