简体   繁体   中英

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?

Using itertools.product :

import itertools
pd.DataFrame(itertools.product(names,pets), columns = ['names', 'pets'])
name=['jack','bob']
pets =['fish','cat','dog','bird']


index = pd.MultiIndex.from_product([name, pets], names = ["name", "pets"])

pd.DataFrame(index = index).reset_index()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM