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

Python Pandas Dataframe How to repeat a value in one column based on length of another column

How do I repeat the values in one column multiple times based on the length of another column? Example: names = [Jack, Bob] and pets=[fish, cat, dog, bird]. I would like the dataframe to be:

    names   pets
0   Jack    fish
1   Jack    cat
2   Jack    dog
3   Jack    bird
4   Bob     fish
5   Bob     cat
6   Bob     dog
7   Bob     bird

How do I repeat the names (which will need to be filled in the names column) for every value in the pets column and then repeat the process for each name in names?

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

>Solution :

Using itertools.product:

import itertools
pd.DataFrame(itertools.product(names,pets), columns = ['names', 'pets'])
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