我正在尝试使用另一个数据框的索引复制一个数据框。例如,假设如下:
basket = pd.DataFrame(columns = ["food_type", "food", "qty"], data=[
["fruit" , "apple", 1],
["fruit" , "pear", 1],
["fruit" , "banana", 1],
["veggie", "carrot", 1],
["veggie", "lettuce", 1]])
basket.set_index(["food_type", "food"], inplace=True)
我正在尝试使用人员列表复制这些行,以便实现以下目标:
target_df = pd.DataFrame(columns = ["person", "food_type", "food", "qty"]
).set_index(["person", "food_type", "food"])
people = ["jane", "john", "joan"]
for person in people:
basket_copy = basket.copy()
basket_copy["person"] = person
basket_copy.set_index("person", append=True, inplace=True)
target_df = target_df.append(basket_copy)
此解决方案有效但看起来很笨重。在 Python 中有更自然的方法吗?我在想象 basket
数据框和 people
数组之间的某种合并。
最佳答案
你可以结合concat
, assign
, 和 set_index
:
df = pd.concat(basket.assign(person=p) for p in people).set_index('person', append=True)
结果输出:
qty
food_type food person
fruit apple jane 1
pear jane 1
banana jane 1
veggie carrot jane 1
lettuce jane 1
fruit apple john 1
pear john 1
banana john 1
veggie carrot john 1
lettuce john 1
fruit apple joan 1
pear joan 1
banana joan 1
veggie carrot joan 1
lettuce joan 1
关于python - 使用所需重复列表将重复行插入到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42938072/