Home > Net >  Is there a pandas way to add a dataframe for each row by a specific column value
Is there a pandas way to add a dataframe for each row by a specific column value

Time:04-17

I have a dataframe here:

    name       role
0   Allen      Director
1   Kendrick   Food
2   Sean       Webmaster
3   Jacob      PR

I also have another dataframe:

    power
0   eat
1   sleep
2   code

Is there a pandas way to add the power dataframe to each member in the team dataframe to make it look like this?

    name      role      power
0   Allen     Director  eat
1   Allen     Director  sleep
2   Allen     Director  code
3   Kendrick  Food      eat
4   Kendrick  Food      sleep
5   Kendrick  Food      code
...

I've tried doing by iterating through the rows but my dataframe is a lot larger than the example I have provided above and I am looking for a pandas approach to do this.

CodePudding user response:

One option is to assign df2.power to df1 as a list, then explode it:

out = df1.assign(power=[df2['power'].tolist()]*len(df1)).explode('power').reset_index(drop=True)

If you have pandas >= 1.2.0., you can cross-merge:

out = df1.merge(df2, how='cross')

Output:

        name       role  power
0      Allen   Director    eat
1      Allen   Director  sleep
2      Allen   Director   code
3   Kendrick       Food    eat
4   Kendrick       Food  sleep
5   Kendrick       Food   code
6       Sean  Webmaster    eat
7       Sean  Webmaster  sleep
8       Sean  Webmaster   code
9      Jacob         PR    eat
10     Jacob         PR  sleep
11     Jacob         PR   code
  • Related