Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading