[英]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].
示例:names = [Jack, Bob] 和 pets=[fish, cat, dog, bird]。 I would like the dataframe to be:
我希望 dataframe 是:
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?如何为 pets 列中的每个值重复名称(需要在名称列中填写),然后为名称中的每个名称重复该过程?
Using itertools.product
:使用
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.