Home > Software engineering >  how to add multiple values ​and make the row repeat for the number of values
how to add multiple values ​and make the row repeat for the number of values

Time:08-12

I have a list of objects by each name and a dataframe like this.

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

Charles = ['smartphone','cake']

John = ['clock','paper']

id name
1 Jimmy
2 Charles
3 John

I would like to use a loop that allows me to obtain the following result.

id name picks
1 Jimmy chair
1 Jimmy table
1 Jimmy pencil
2 Charles smartphone
2 Charles cake
3 John clock
3 John paper

CodePudding user response:

You can assign and explode:

values = {'Jimmy': Jimmy, 'Charles': Charles, 'John': John}

out = df.assign(picks=df['name'].map(values)).explode('picks')

Or set up a DataFrame, stack and merge:

values = {'Jimmy': Jimmy, 'Charles': Charles, 'John': John}

out = df.merge(
         pd.DataFrame.from_dict(values, orient='index')
           .stack().droplevel(1).rename('picks'),
         left_on='name', right_index=True
        )

output:

   id     name       picks
0   1    Jimmy       chair
0   1    Jimmy       table
0   1    Jimmy      pencil
1   2  Charles  smartphone
1   2  Charles        cake
2   3     John       clock
2   3     John       paper

CodePudding user response:

We can make a dataframe relating names to picks, then join them together with merge:

import pandas as pd

#dataframe from question
df = pd.DataFrame()
df["id"] = [1, 2, 3]
df["name"] = ["Jimmy", "Charles", "John"]

#dataframe relating names to picks.
picks_df = pd.DataFrame()
picks_df["name"] = ["Jimmy", "Jimmy", "Jimmy", "Charles", "Charles", "John", "John"]
picks_df["picks"] = ["chair", "table", "pencil", "smartphone", "cake", "clock", "paper"]

#Merge and print
print(pd.merge(df, picks_df, on="name"))
  • Related