John Robot
John Robot

Reputation: 1

Pandas Dataframe Enlargement

I have a dataframe with the following format

Name    Entries Price
John      2       10 
Mary      3       12

And I want to transform it to a dataframe where every row has entry value 1

Name    Entries Price
John      1       10 
John      1       10  
Mary      1       12
Mary      1       12
Mary      1       12

My solution to it was to iterate throughout every row in the original frame, get the total entries for that row, N, and then I append new rows N times to a new dataframe. However this is pretty in inefficient. Do you guys have any idea how to make it faster?

Upvotes: 0

Views: 55

Answers (1)

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use -

op = df.reindex(df.index.repeat(df['Entries'])).reset_index(drop=True)
op['Entries'] = 1

Output

    Name    Entries Price
0   John    1   10
1   John    1   10
2   Mary    1   12
3   Mary    1   12
4   Mary    1   12

Upvotes: 1

Related Questions