Loop to add multiple values ​and make the row repeat in a dataframe

Viewed 29

I have a list of objects by each name and a dataframe like this.(it's a big one)

Jason = ['chair','table','pencil']

Miguel = ['smartphone','cake']

Johana = ['clock','paper']

id name
1 Jason
2 Miguel
3 Johana

I would like to use a loop that allows me to obtain the following result because I have a large database in which many rows have to be added for each name index. I would like to have the following result with a loop.

id name picks
1 Jason chair
1 Jason table
1 Jason pencil
2 Miguel smartphone
2 Miguel cake
3 Johana clock
3 Johana paper
1 Answers
import pandas as pd

data = {
    'Jason': ['chair','table','pencil'],
    'Miguel': ['smartphone','cake'],
    'Johana': ['clock','paper']
}

df1 = pd.DataFrame([[1, 'Jason'], [2, 'Miguel'], [3, 'Johana']], columns=['id', 'name'])

pairs = []
for i, (id_, name) in df1.iterrows():
    pairs.extend([[id_, name, k] for k in data[name]])
df = pd.DataFrame(pairs, columns=['id', 'name', 'picks'])
print(df)

prints

index id name picks
0 1 Jason chair
1 1 Jason table
2 1 Jason pencil
3 2 Miguel smartphone
4 2 Miguel cake
5 3 Johana clock
6 3 Johana paper
Related