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?
CodePudding user response:
Using itertools.product:
import itertools
pd.DataFrame(itertools.product(names,pets), columns = ['names', 'pets'])
CodePudding user response:
name=['jack','bob']
pets =['fish','cat','dog','bird']
index = pd.MultiIndex.from_product([name, pets], names = ["name", "pets"])
pd.DataFrame(index = index).reset_index()
