简体   繁体   English

Python Pandas Dataframe 如何根据另一列的长度重复一列中的值

[英]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.

相关问题 根据列值重复 pandas DataFrame 中的行 - Repeat rows in a pandas DataFrame based on column value 如何根据列值重复熊猫数据框记录 - How to repeat pandas dataframe records based on column value 如何将一列除以另一列,其中一个数据帧的列值对应于 Python Pandas 中另一个数据帧的列值? - How to divide one column by another where one dataframe's column value corresponds to another dataframe's column's value in Python Pandas? Python Pandas:将一列的值检查到另一列 dataframe - Python Pandas: checking value of one column into column of another dataframe Pandas/Python:根据另一列中的值设置一列的值 - Pandas/Python: Set value of one column based on value in another column 如何根据 Pandas Dataframe 中的另一列对一列进行排序? - How to sort one column based on another column in Pandas Dataframe? 如何根据 Pandas 数据框中的另一列值添加列? - How to add column based on another column value in Pandas dataframe? Python Pandas根据一列中的值创建新列,而另一列中为空白 - Python Pandas new column based on value in one column and blank in another 根据另一列(Python,Pandas)中的值删除一列的重复项 - Drop duplicates of one column based on value in another column, Python, Pandas 根据 Pandas 中的 id 将列值从一个数据帧复制到另一个数据帧 - Copy column value from one dataframe to another based on id in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM